如何从使用group by命令检索的结果中获取每组中的第一条记录

时间:2011-03-07 20:53:31

标签: sql-server-2008

假设我的输入是:

ID  GroupID  Qty
1         1  100
2         1  200
3         1  300
4         2  98
5         2  198
6         3  175
7         3  275
8         3  375
9         4  215

输出应为

ID   GroupID    Qty
 1         1    100
 4         2    98
 6         3    175
 9         4    215

任何人都可以帮我解决如何使用SQL Server T-SQL查询吗?

3 个答案:

答案 0 :(得分:33)

declare @T table (ID int, GroupID int, Qty int)
insert into @T values
(1, 1, 100),
(2, 1, 200),
(3, 1, 300),
(4, 2, 98),
(5, 2, 198),
(6, 3, 175),
(7, 3, 275),
(8, 3, 375),
(9, 4, 215)

;with cte as
(
  select
    ID,
    GroupID,
    Qty,
    rank() over(partition by GroupID order by ID) as rn
  from @T
)  
select ID, GroupID, Qty
from cte
where rn = 1

答案 1 :(得分:5)

修改

SELECT 
    MIN(ID) ,
    GroupID,
    (SELECT TOP 1 Qty FROM @TABLE T2 WHERE T2.ID = MIN(T1.ID))
FROM 
    @TABLE T1
GROUP BY
    GroupID

输入

 ID GroupID   Qty
    1   1   100
    2   1   200
    3   1   300
    4   2   98
    5   2   198
    6   3   175
    7   3   275
    8   3   375
    9   4   215

输出

1   1   100
4   2   98
6   3   175
9   4   215

答案 2 :(得分:2)

我认为最好和更灵活的方法是使用ROW_NUMBER()。 下面我已经测试了您的示例,只需将 tmpTable 替换为您的表名:

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

详细了解如何使用ROW_NUMBER:https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql