Search code examples
sql-serverfetchlimitrowswindow-functions

Group By selecting fixed rows returned and ignoring the top row SQL Server


I have a table:

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

I want to return two records per customer ignoring the top purchase:

John                  5
John                  3
Sally                 3
Sally                 2 

Solution

  • With ROW_NUMBER() window function:

    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