[英]Filter by grouping two columns
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,但没有得到正确的结果。 (此表中还有其他一些列)此musu非常简单,但我无法做到。
任何帮助,将不胜感激。
您可以使用聚合。 如果您不关心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;
您可以为此使用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
这将选择ID, Type
分区中Status
值最小的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.