Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于第二列中的值的组合获取计数_Sql_Sql Server - Fatal编程技术网

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