简体   繁体   English

通过分组两列进行过滤

[英]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 我想按ID和类型过滤此数据组

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 1和type1有多个记录,我只想显示此组合的一个记录(与状态无关)。

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. 我尝试使用distinct和group by,但没有得到正确的结果。 (there are some other columns as well in this table) This musu be very simple but I am not able to do it. (此表中还有其他一些列)此musu非常简单,但我无法做到。

Any help would be appreciated. 任何帮助,将不胜感激。

You can use aggregation. 您可以使用聚合。 If you don't care about status , just use min() : 如果您不关心status ,请使用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: 如果“不在乎”实际上意味着“随机”,则使用row_number()代替:

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: 您可以为此使用ROW_NUMBER

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. 这将选择ID, Type分区中Status值最小的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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