SQL查询以从组中返回特定行

时间:2018-11-27 17:10:17

标签: sql sql-server

使用SQL Server

我的问题最好通过查看下表来描述,我想将所有突出显示为红色的行返回。我需要按internal_id对所有行进行分组,因为这可以重复几次,并且从该结果集中显示具有最小id值的行。还有一个限制,即数据集必须为“ TEST1”且类型为“ CHANGE”。

example table

2 个答案:

答案 0 :(得分:1)

使用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);

答案 1 :(得分:1)

添加了测试数据。

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