通过分组两列进行筛选

时间:2016-03-17 11:20:33

标签: sql sql-server filter group-by distinct

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

我有以上数据

我想按ID和类型

过滤此数据组

例如,如果Id 1和type1有多个记录,我想只显示该组合的一条记录(无论状态如何)。

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

我尝试使用distinct和group by,但没有得到正确的结果。 (此表中还有其他一些列) 这个音乐很简单,但我无法做到。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用聚合。如果您不关心status,请使用min()

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

如果"不关心"真的意思是"随机",然后使用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;

答案 1 :(得分:1)

您可以使用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

这将选择Status分区中具有最小ID, Type值的记录。

相关问题