MySQL CROSSTAB或PIVOT查询

时间:2015-02-05 06:24:11

标签: 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将汇总所有Os,而Totals将汇总所有NAs)来自上表。我正在使用MySQL数据库。

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

1 个答案:

答案 0 :(得分:1)

简单回答,但我刚喝了一杯咖啡......

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