简体   繁体   中英

Need to select 1 row from each group in sql

am trying to do this query. This is what I have.

My table is: Table

QId    InternalId      type.     priority       userid
100       100              1            0                X101
100       100              1            1                X102
100       100              2            0                X103
100       100              2            0                X104
100       100              2            0                X105
100       100              3            0                X106
100       100              3            0                X107
101       101              2            1                X114
101       101              2            0                X115
101       101              3            0                X116
101       101              3            0                X117

For QId and InternalId we have type 1,2,3. I need 1 row for each group based type. Here condition is if priority is 1 then we need take that record. if priority is not set need to take first record.

I need result like below table

QId    InternalId      type.     priority       userid
100       100              1            1                X102
100       100              2            0                X103
100       100              3            0                x106
101       101              2            1                X114
101       101              3            0                X116

Can you please help me out in this

Just use row_number() :

select t.*
from (select t.*,
             row_number() over (partition by QId, InternalId, type order by (select null)) as seqnum
      from t
     ) t
where seqnum = 1;

You can try using row_number()

select * from
(
select *, row_number() over(partition by qid, internalid, type order by priority desc) as rn
from tablename
)A where rn=1

use row_number() window function

select t.* from (select *,row_number()over(partition by QId,InternalId,type order by case when priority=1 then 1 else 2 end) rn
) where t.rn=1

Another approach can be WITH TIES like following.

select top 1 with ties *
from @table
order by row_number() over (partition by QId, InternalId, type order by (select 1))

Online Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM