使用MySQL。我有一张看起来像这样的表:
rawID | a1a | a1b | a2a | a2b | a2c | ...
1 | 2 | 0 | 0 | 0 | 2 | ...
2 | 2 | 2 | 0 | 0 | 0 | ...
3 | 0 | 1 | 1 | 1 | 2 | ...
4 | 2 | 1 | 2 | 1 | 2 | ...
*字段的可能值在单独的“响应”表中预定义,范围为0-2。
我想要一个结果,让我看到每个字段的每个值的出现。我见过类似的问题,但只讨论过一个领域。
我希望我的结果看起来像这样:
response | a1a | a1b | a2a | a2b | a2c | ...
0 | 1 | 1 | 2 | 2 | 1 | ...
1 | 0 | 2 | 1 | 2 | 0 | ...
2 | 3 | 1 | 1 | 0 | 3 | ...
此表格包含每个字段的每个值(“响应”)的次数。
谢谢你们,
答案 0 :(得分:1)
试试这个:
SELECT
response,
sum(a1a = response) a1aCount,
sum(a1b = response) a1bCount,
sum(a2a = response) a2aCount,
sum(a2b = response) a2bCount,
sum(a2c = response) a2cCount
FROM t, r
GROUP BY response
输出:
| RESPONSE | A1ACOUNT | A1BCOUNT | A2ACOUNT | A2BCOUNT | A2CCOUNT |
|----------|----------|----------|----------|----------|----------|
| 0 | 1 | 1 | 2 | 2 | 1 |
| 1 | 0 | 2 | 1 | 2 | 0 |
| 2 | 3 | 1 | 1 | 0 | 3 |
小提琴here。
无论response
表格中的项目数量是多少,这都可以。
答案 1 :(得分:0)
我认为这应该有效(我们假设您的表名是“响应”):
SELECT 0 as response, SUM(r.a1a = 0) as a1a, SUM(r.a1b = 0) as a1b,
SUM(r.a2a = 0) as a2a, SUM(r.a2b = 0) as a2b FROM responses r
UNION
SELECT 1 as response, SUM(r.a1a = 1) as a1a, SUM(r.a1b = 1) as a1b,
SUM(r.a2a = 1) as a2a, SUM(r.a2b = 1) as a2b FROM responses r
UNION
SELECT 2 as response, SUM(r.a1a = 2) as a1a, SUM(r.a1b = 2) as a1b,
SUM(r.a2a = 2) as a2a, SUM(r.a2b = 2) as a2b FROM responses r