【问题标题】:Group By selecting fixed rows returned and ignoring the top row SQL Server通过选择返回的固定行并忽略顶行 SQL Server 进行分组
【发布时间】:2020-09-02 06:48:54
【问题描述】:

我有一张桌子:

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 fetch limit rows window-functions


    【解决方案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
    

    【讨论】:

    • 谢谢你,forpas。
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2012-01-28
    相关资源
    最近更新 更多