简体   繁体   中英

Filter by grouping two columns

ID  Type    Status  
------------------------
1   Type1   Success 
1   Type1   Fail    
1   Type2   Fail    
2   Type3   Fail    
3   Type1   Success 

I have above data

I want to filter this data group by Id and Type

For example, if there are multiple records for Id 1 and type1, I want to show only one record of this combination (irrespective of the status).

ID  Type    Status  
------------------------
1   Type1   Success 
1   Type2   Fail    
2   Type3   Fail    
3   Type1   Success 

I tried using distinct and group by, but not getting proper result. (there are some other columns as well in this table) This musu be very simple but I am not able to do it.

Any help would be appreciated.

You can use aggregation. If you don't care about status , just use min() :

select id, type, min(status) as status
from t
group by id, type;

If "don't care" really means "random", then use row_number() instead:

select id, type, status
from (select t.*,
             row_number() over (partition by id, type order by newid()) as seqnum
      from t
     ) t
where seqnum = 1;

You can use ROW_NUMBER for this:

SELECT ID, Type, Status, ... rest of the fields here
FROM (
  SELECT ID, Type, Status, ... rest of the fields here, 
         ROW_NUMBER() OVER (PARTITION BY ID, Type 
                            ORDER BY Status) AS rn
  FROM mytable) t
WHERE t.rn = 1

This will pick the record having the minimum Status value within the ID, Type partition.

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