如何使用group by计算数据

时间:2015-11-01 11:46:06

标签: mysql

我有表customer_survey

     User_id | Question 1 | Question 2 | Question 3
      1           GOOD          BAD          WORST
      2           GOOD          GOOD         GOOD
      3           WORST         GOOD         WORST
      4           BAD           BAD          BAD
      5           BAD           GOOD         GOOD
      6           GOOD          BAD          GOOD
      7           GOOD          BEST         GOOD
      8           GOOD          WORST        GOOD

我有表score

      Id    description
      1      WORST
      2      BAD
      3      GOOD 
      4      BEST

结果:

               WORST     BAD   GOOD    BEST
 Question 1      1         2     5       0
 Question 2      1         3     3       1 
 Question 3      1         1     5       0

我为此感到困惑。

1 个答案:

答案 0 :(得分:0)

简单但麻烦的方法:

SELECT
'Question 1' AS QUESTION,
COUNT(CASE customer_survey.question1 WHEN 'WORST' THEN 1 ELSE NULL END) AS WORST
FROM
customer_survey
UNION ALL
(SELECT
'Question 2' AS QUESTION,
COUNT(CASE customer_survey.question2 WHEN 'GOOD' THEN 1 ELSE NULL END) AS GOOD
FROM
customer_survey)
UNION ALL
(SELECT
'Question 3' AS QUESTION,
COUNT(CASE customer_survey.question3 WHEN 'BAD' THEN 1 ELSE NULL END) AS BAD
FROM
customer_survey)
UNION ALL
(SELECT
'Question 4' AS QUESTION,
COUNT(CASE customer_survey.question4 WHEN 'BEST' THEN 1 ELSE NULL END) AS BEST
FROM
customer_survey)