使用生成的列名称对翻转表中的列值进行求和

时间:2016-05-28 12:24:46

标签: mysql

我有以下 MySQL代码

    select question, 
      sum(case when value = '1' then 1 else 0 end) '1',
      sum(case when value = '2' then 1 else 0 end) '2',
      sum(case when value = '3' then 1 else 0 end) '3',
      sum(case when value = '4' then 1 else 0 end) '4',
      sum(case when value = '5' then 1 else 0 end) '5',
      sum(case when value = '6' then 1 else 0 end) '6',
      sum(case when value = '7' then 1 else 0 end) '7',
      sum(case when value = '8' then 1 else 0 end) '8',
      sum(case when value = '9' then 1 else 0 end) '9',
      sum(case when value = '10' then 1 else 0 end) '10',
      count(value) AS total -- this line should be edited
    from
    (
        select answer1 value, 'answer1' question
        from questionaire
        union all
        select answer2 value, 'answer2' question
        from questionaire
        union all
        select answer3 value, 'answer3' question
        from questionaire
    ) src
    group by question

这是一个select语句,用于翻转格式如下的表:

id   |  e-mail           | answer1 | answer2 | answer3
------------------------------------------------------
1    |  test@example.com |    1    |    6    |   8
2    |  test2@example.com|    1    |    1    |   7
3    |  test2@example.com|    1    |    1    |   0

翻转的表格看起来像这样

question | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | total
---------------------------------------------------------
answer 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0  |   3
answer 2 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0  |   3
answer 3 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0  |   3

有一个total列可以计算所有值,但是我想要sum列出之前列的所有值。因为当有人跳过问题时,它会被计为零,而总和中的总和将是错误的(参见表格,答案3)。总数为3,应为2

我的问题是如何在总列中总结1到10之间的所有值?

1 个答案:

答案 0 :(得分:1)

我会把它改为:

sum(value in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10') )

或者,或许更简单地说:

sum(value > '0')