通过对两列进行分组进行过滤
Filter by grouping two columns
ID Type Status
------------------------
1 Type1 Success
1 Type1 Fail
1 Type2 Fail
2 Type3 Fail
3 Type1 Success
我有以上数据
我想按 Id 和 Type 过滤这个数据组
比如Id 1和type1有多条记录,我想只显示一条该组合的记录(不考虑状态)
ID Type Status
------------------------
1 Type1 Success
1 Type2 Fail
2 Type3 Fail
3 Type1 Success
我尝试使用 distinct 和 group by,但没有得到正确的结果。 (此 table 中还有其他一些专栏)
这个musu很简单但是我做不到
如有任何帮助,我们将不胜感激。
您可以使用聚合。如果你不关心status
,就用min()
:
select id, type, min(status) as status
from t
group by id, type;
如果"don't care"真的意味着"random",那么用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
值的记录。
ID Type Status
------------------------
1 Type1 Success
1 Type1 Fail
1 Type2 Fail
2 Type3 Fail
3 Type1 Success
我有以上数据
我想按 Id 和 Type 过滤这个数据组
比如Id 1和type1有多条记录,我想只显示一条该组合的记录(不考虑状态)
ID Type Status
------------------------
1 Type1 Success
1 Type2 Fail
2 Type3 Fail
3 Type1 Success
我尝试使用 distinct 和 group by,但没有得到正确的结果。 (此 table 中还有其他一些专栏) 这个musu很简单但是我做不到
如有任何帮助,我们将不胜感激。
您可以使用聚合。如果你不关心status
,就用min()
:
select id, type, min(status) as status
from t
group by id, type;
如果"don't care"真的意味着"random",那么用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
值的记录。