MySQL CROSSTAB 或 PIVOT 查询

标签 mysql sql

我有一个表格,其中列中的分数为 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/

相关文章:

php - 如何防止重复记录?

php - 使用相同查询从多个表返回用户数

mysql - 汇总值,即使它们不存在于第二个表中

mysql - 如何按表中的两个相关值排序

mysql - 返回表sql的函数

php - MySql 数据库连接压缩

sql - 使用 MySQL 将任务分配给工作进程的正确方法

c# - LINQ DB Arithmetic 必须具有通用类型(日期比较

sql - 如何优化 ABAP 查询

sql - ADODB RecordSet RecordCount 不返回有用信息