I have this table. All values are 0 or 1.
| a | b | c |
|---|---|---|
| 1 | 0 | 0 |
| 1 | 1 | 0 |
| 0 | 1 | 0 |
| 1 | 1 | 1 |
and I want this one
| a | b | c | |
|---|---|---|---|
| a | 3 | 2 | 1 |
| b | 2 | 3 | 1 |
| c | 1 | 1 | 1 |
This last table answers to the question how many rows have {raw} and {col} set to 1. For example, there are 2 rows where a = b = 1 in the first table, so cell(a,b) = 2.
I have a query that is not suitable for large tables. Is it possible to make it simpler?
SELECT
'a' AS ' ',
SUM(a) AS a,
(SELECT SUM(b) FROM tab WHERE a = 1) AS b,
(SELECT SUM(c) FROM tab WHERE a = 1) AS c
FROM
tab
UNION
SELECT
'b',
(SELECT SUM(a) FROM tab WHERE b = 1),
SUM(b),
(SELECT SUM(c) FROM tab WHERE b = 1)
FROM
tab
UNION
SELECT
'c',
(SELECT SUM(a) FROM tab WHERE c = 1),
(SELECT SUM(b) FROM tab WHERE c = 1),
SUM(c)
FROM
tab