具有GROUP BY计数的MySQL CASE

时间:2015-01-29 07:12:33

标签: mysql group-by case

我有这三个查询

SELECT COUNT(question_id) AS correct_count, uID FROM mytable  WHERE id
>= 0 AND id <= 1000 AND correct = 1 AND answer_id IS NOT NULL GROUP BY user_id


SELECT COUNT(question_id) AS incorrect_count, uID FROM mytable  WHERE id >= 0 AND id <= 1000 AND correct !=1 AND answer_id IS NOT NULL GROUP BY user_id

SELECT COUNT(question_id) AS null_count, uID FROM mytable  WHERE id >= 0 AND id <= 1000 AND answer_id IS NULL GROUP BY user_id

如何使用CASE或IF将其作为单个查询加入?

2 个答案:

答案 0 :(得分:0)

SELECT user_id, 
       sum(id >= 0 AND id <= 1000 AND correct = 1 AND answer_id IS NOT NULL) AS correctCnt, 
       sum(id >= 0 AND id <= 1000 AND correct !=1 AND answer_id IS NOT NULL) AS incorrectCnt,
       sum(id >= 0 AND id <= 1000 AND answer_id IS NULL) as nullCnt
FROM mytable  
GROUP BY user_id

答案 1 :(得分:0)

count仅计算非null项,因此您可以将where子句转换为case表达式,当它们不匹配时返回null

SELECT   user_id,
         COUNT (CASE WHEN id >= 0 AND id <= 1000 AND correct = 1 AND answer_id IS NOT NULL THEN 1 ELSE NULL) AS correct_count, 
         COUNT (CASE WHEN id >= 0 AND id <= 1000 AND correct !=1 AND answer_id IS NOT NULL THEN 1 ELSE NULL) AS incorrect_count,
         COUNT (CASE WHEN WHERE id >= 0 AND id <= 1000 AND answer_id IS NULL) AS null_count
FROM     mytable  
GROUP BY user_id

请注意,所有这些case语句都有一些条件,因此可以将它们提取到where子句:

SELECT   user_id,
         COUNT (CASE WHEN correct = 1 AND answer_id IS NOT NULL THEN 1 ELSE NULL) AS correct_count, 
         COUNT (CASE WHEN correct !=1 AND answer_id IS NOT NULL THEN 1 ELSE NULL) AS incorrect_count,
         COUNT (CASE WHEN WHERE answer_id IS NULL THEN 1 ELSE NULL) AS null_count
FROM     mytable
WHERE    id >= 0 AND id <= 1000  
GROUP BY user_id