Find the top two rows within each group

Maggie 40 Reputation points
2023-01-27T02:13:44.3266667+00:00

Hello, I need some help with SQL.

I have a table that contains three columns A, B, and C. I need to group according to columns A and B, and then sort according to column C to get the top two records of each group. I cannot figure out how to do it. I appreciate any help.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,708 questions
0 comments No comments
{count} votes

Accepted answer
  1. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-01-27T02:18:49.4566667+00:00

    Hi @Maggie

    You only need one analytical ranking function. You can try this query.

    ;with CTE as(
      select A,B,C,row_number()over(partition by A,B order by C) as num from table)
    select * from CTE where num < 3; 
    
    

    If you still have problems, you can provide your source data and the results you expect to output.

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful