Sql 基于第二列中的值的组合获取计数
我的表格格式如下:Sql 基于第二列中的值的组合获取计数,sql,sql-server,Sql,Sql Server,我的表格格式如下: Id Code 1 A 1 B 2 A 3 A 3 C 4 A 4 B Code Count A,B 2 -- Row 1,2 and Row 6,7 A 1 -- Row 3 A,C 1 -- Row 4 我试图获得如下代码组合的数量: Id Code 1 A 1 B 2 A 3 A 3 C 4 A 4 B Code Count A,B 2 -- Row 1,2 an
Id Code
1 A
1 B
2 A
3 A
3 C
4 A
4 B
Code Count
A,B 2 -- Row 1,2 and Row 6,7
A 1 -- Row 3
A,C 1 -- Row 4
我试图获得如下代码组合的数量:
Id Code
1 A
1 B
2 A
3 A
3 C
4 A
4 B
Code Count
A,B 2 -- Row 1,2 and Row 6,7
A 1 -- Row 3
A,C 1 -- Row 4
我无法得到组合结果。我所能做的就是分组,但我不会得到基于组合的ID数。您需要以某种方式聚合行,然后执行两次。代码如下所示:
select codes, count(*) as num_ids
from (select id, group_concat(code order by code) as codes
from t
group by id
) id
group by code;
group\u concat()
可能拼写为listag()
或string\u agg()
,具体取决于数据库
在SQL Server中,使用string\u agg()
:
用您正在使用的数据库标记您的问题。它是MS SQL server