Reputation: 229
I ve following table:
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
Now I'd like to count pairs and unique categories in the following way: (A,B) = 2, (A)=1, (A,C) = 1. Is it possible to write sql query which give such result?
Upvotes: 1
Views: 302
Reputation: 180927
In MySQL, you can simply form all the groups using GROUP_CONCAT
in a subquery, and count them in an outer query;
SELECT categories, COUNT(*) count
FROM (
SELECT GROUP_CONCAT(category ORDER BY category) categories
FROM mytable
GROUP BY `group`
) z
GROUP BY categories;
In TSQL, GROUP_CONCAT
doesn't exist, so you can use a trick from 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;
Upvotes: 2