How to get first record out of each group from the result retrieved by using group by command

前端 未结 3 1256
误落风尘
误落风尘 2020-12-09 04:38

Suppose if my Input is:

ID  GroupID  Qty
1         1  100
2         1  200
3         1  300
4         2  98
5         2  198
6         3  175
7         3  27         


        
3条回答
  •  星月不相逢
    2020-12-09 05:03

    The best and more flexible way in my opinion would be to use ROW_NUMBER(). The below I've tested for your example, just replace tmpTable with your table name:

    SELECT a.* FROM tmpTable a INNER JOIN 
    (SELECT    ROW_NUMBER() over(PARTITION BY GroupID ORDER BY ID, GroupID) AS SEQ, tmpTable.*
    FROM            tmpTable) b
    ON a.ID = b.ID AND a.GroupID = b.GroupID
    WHERE b.SEQ = 1
    

    read more about how to use ROW_NUMBER: https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql

提交回复
热议问题