组 通过选择固定的行返回,而忽略最上面的行 SQL Server

问题描述 投票:0回答:1

我有一个表。

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-server group-by fetch limit rows
1个回答
1
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.