我有一个表格,其中列中的分数为 1,0,结果为 NA 作为答案。随着为所有三个答案提交更多分数,表中的数据将继续增长。
|id | username | answer1 | answer2 | answer3 |
--------------------------------------------
| 1 | John | 1 | 0 | 1 |
| 2 | Mike | NA | 1 | 1 |
| 3 | Jill | 1 | NA | 0 |
| 4 | Mary | 1 | 1 | 1 |
我正在尝试创建一个选择查询,它将显示上表中列出的结果(Total1 将所有 1 求和,Total 2 将所有 O 求和,Totals 将所有 NA 求和)。我正在使用 MySQL 数据库。
|questions | total_1 | total_0 |total_NA|
----------------------------------------
| answer1 | 3 | 0 | 1 |
| answer2 | 2 | 1 | 1 |
| answer3 | 3 | 0 | 0 |
最佳答案
简单的回答,但我刚喝了一杯咖啡......
select 'answer1' as questions,
sum(case when answer1 = 1 then 1 end) as total_1,
sum(case when answer1 = 0 then 1 end) as total_0,
sum(case when answer1 = NA then 1 end) as total_NA
from tablename
UNION ALL
select 'answer2' as questions,
sum(case when answer2 = 1 then 1 end) as total_1,
sum(case when answer2 = 0 then 1 end) as total_0,
sum(case when answer2 = NA then 1 end) as total_NA
from tablename
etc...
关于MySQL CROSSTAB 或 PIVOT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337489/