简体   繁体   English

MySQL CROSSTAB或PIVOT查询

[英]MySQL CROSSTAB or PIVOT Query

I have a table with scores in columns with 1,0,and NA for answer as results. 我有一个表格,其中分数列为1,0,结果为NA。 The data in the table will continue to grow as more scores are submitted for all three answer. 随着针对这三个答案提交的分数越来越多,表格中的数据将继续增长。

   |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    |

I am trying to create a select query that will display the results listed below (Total1 will sum all 1s, Total 2 will sum all Os, and Totals will sum all NAs) from the table above. 我正在尝试创建一个选择查询,该查询将显示上表中列出的结果(总计1将总计1,总计2将总计所有O,总计将总计所有NA)。 I am using a MySQL database. 我正在使用MySQL数据库。

   |questions | total_1  | total_0 |total_NA|
    ----------------------------------------
   | answer1  |    3     |    0    |   1    |
   | answer2  |    2     |    1    |   1    |
   | answer3  |    3     |    0    |   0    |

Simple answer, but I've just had one cup of coffee yet... 简单的答案,但我刚喝了一杯咖啡...

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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM