我想获得不同列中具有不同值的行的组合计数。
采样数据如下:
+------+---------+---------+
| GUID | Column1 | Column2 |
+------+---------+---------+
| XXX | A | aaa |
| XXX | B | bbb |
| YYY | C | ccc |
| YYY | D | ddd |
| XXX | A | aaa |
| XXX | B | bbb |
+------+---------+---------+
我期待以下结果。所以XXX应该是2,因为我们有2条记录,其中Column1 = A,Column2 = aaa,Column1 = B,Column2 = bbb(两个不同列值的组合)
XXX 2
YYY 1
答案 0 :(得分:0)
您可以按GUID
和Column2
进行分组,然后取最大值count(*)
来获得组合数:
declare @tmp table ([GUID] varchar(3), Column1 varchar(1), Column2 varchar(3))
insert into @tmp values ('XXX','A','aaa'),('XXX','B','bbb'),('YYY','C','ccc'),
('YYY','D','ddd'),('XXX','A','aaa'),('XXX','B','bbb')
select T.[GUID], max(T.cnt) as count_combinations
from (
select [GUID], Column2, count(*) as cnt
from @tmp
group by [GUID], Column2
) T
group by T.[GUID]
结果: