我跟着表:
id | group | decision | category
___ _______ _________
1 | 1111 | yes | A
2 | 1111 | yes | B
3 | 2222 | no | A
4 | 3333 | yes | A
5 | 3333 | yes | C
6 | 4444 | no | A
7 | 4444 | no | B
现在我想以下列方式计算对和唯一类别:(A,B)= 2,(A)= 1,(A,C)= 1.是否可以编写sql查询给出这样的结果?
答案 0 :(得分:2)
在MySQL中,您可以在子查询中使用GROUP_CONCAT
简单地形成所有组,并在外部查询中对它们进行计数;
SELECT categories, COUNT(*) count
FROM (
SELECT GROUP_CONCAT(category ORDER BY category) categories
FROM mytable
GROUP BY `group`
) z
GROUP BY categories;
在TSQL中,GROUP_CONCAT
不存在,因此您可以使用here
SELECT categories, COUNT(*) count
FROM (
SELECT
STUFF((SELECT ',' + mt.category
FROM mytable mt
WHERE m.[group] = mt.[group]
ORDER BY mt.category
FOR XML PATH(''), TYPE).
value('.', 'NVARCHAR(MAX)'), 1, 1, '') categories
FROM mytable m
GROUP BY [group]
) z
GROUP BY categories;