SQL按组连接计数

时间:2014-03-20 16:24:55

标签: sql sql-server

假设我的数据格式如下:

id   item
1      a
1      b
1      c
2      a
2      b
3      x
3      y
3      z
4      a
4      b
4      c

有没有办法动态建立"项目"的所有组合的列表。对于给定的ID并计算它们?输出看起来像这样:

combo count
abc    2
ab     1
xyz    1

这是我可以在Excel中轻松完成的工作,但我不确定是否有办法在SQL中自动化它。

2 个答案:

答案 0 :(得分:2)

您可以通过将每个id的值连接在一起来实现此目的。这在SQL Server中很难吃,因为它不支持group_concat()listagg()或类似功能。您可以使用相关子查询来执行此操作。

然后,只计算组合:

select combo, count(*)
from (select (select item
              from table t2
              where t2.id = t.id
              order by item
              for xml path ('')
             ) as combo
      from table t
      group by id
     ) c
group by combo;

答案 1 :(得分:1)

试试这个:

declare @t table (id int, item char(1))

insert into @t select '1',      'a'
insert into @t select '1',      'b'
insert into @t select '1',      'c'
insert into @t select '2',      'a'
insert into @t select '2',      'b'
insert into @t select '3',      'x'
insert into @t select '3',      'y'
insert into @t select '3',      'z'
insert into @t select '4',      'a'
insert into @t select '4',      'b'
insert into @t select '4',      'c'

;with d as (
  select distinct id from @t
),
groups as (
  select
    id, 
    name = (select item from @t t where d.id = t.id for xml path(''))
  from d
)
select name, [count] = count(*) 
from groups g
group by name
order by 2 desc