Using 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. There is a further restriction that the dataset must = 'TEST1' and the type = 'CHANGE'.
Use row_number()
function :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.