[英]SQL query to return a specific row from a group
Using SQL Server 使用SQL Server
The problem I have is best described by looking at the table below, I want to return all the rows highlighted red. 可以通过查看下表来最好地描述我遇到的问题,我想返回所有突出显示为红色的行。 I need to group all the rows by internal_id as this can be repeated several times and from that result set display the row with the smallest id value. 我需要按internal_id对所有行进行分组,因为这可以重复几次,并且从该结果集中显示具有最小id值的行。 There is a further restriction that the dataset must = 'TEST1' and the type = 'CHANGE'. 还有一个限制,即数据集必须为“ TEST1”且类型为“ CHANGE”。
Use row_number()
function : 使用row_number()
函数:
select top (1) with ties t.*
from table t
where dataset = 'test1' and type = 'change'
order by row_number() over (partition by internal_id order by id);
added with test data. 添加了测试数据。
create table #temp_1
( dataset varchar(7) null
,id int null
,duration int null
,type varchar(10) null
,internal_id int null
)
insert into #temp_1 values
('TEST1',97,61,'cOMPLETE',7)
,('TEST1',98,61,'cHANGE',13)
,('TEST1',102,61,'cHANGE',16)
,('TEST1',103,611,'cHANGE',15)
,('TEST1',107,601,'cHANGE',5)
,('TEST1',110,601,'cHANGE',25)
,('TEST1',111,613,'cHANGE',35)
,('TEST1',113,615,'cHANGE',45)
,('TEST1',193,619,'cHANGE',5)
,('TEST1',200,620,'cHANGE',51)
select *
from (
SELECT *
,Rank_dense = dense_rank() over(partition by type order by internal_id asc)
,Rank_regular = rank() over(partition by type order by internal_id asc)
from #temp_1
where dataset = 'Test1' and type = 'change'
) a
where Rank_dense = 1 -- or Rank_dense
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.