首页 > 解决方案 > 通过选择返回的固定行并忽略顶行 SQL Server 进行分组

问题描述

我有一张桌子:

Customer           Purchase
John                 5
John                 8
John                 3
John                 1  
Sally                3
Sally                5
Sally                2

我想为每个客户返回两条记录,忽略最高购买:

John                  5
John                  3
Sally                 3
Sally                 2 

标签: sql-serverfetchlimitrowswindow-functions

解决方案


ROW_NUMBER()窗口功能:

select t.customer, t.purchase
from (
  select *, row_number() over (partition by customer order by purchase desc) rn
  from tablename
) t
where t.rn between 2 and 3

推荐阅读