如何从使用 group by 命令检索的结果中获取每个组的第一条记录 [英] How to get first record out of each group from the result retrieved by using group by command
本文介绍了如何从使用 group by 命令检索的结果中获取每个组的第一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的输入是:
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
查询来做到这一点?
Can any one help me how to do it with SQL Server T-SQL
query?
推荐答案
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
这篇关于如何从使用 group by 命令检索的结果中获取每个组的第一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文