如何显示所有Case When Then记录即使在MySQL中为NULL

时间:2017-06-04 00:10:02

标签: mysql case case-when

我必须显示有多少用户投票支持投票 2 ,但在年龄范围内分开。

我当前的查询工作正常;但是当特定范围内没有任何用户时,我遇到了麻烦。例如,如果年龄在40-49岁之间的用户没有投票赞成民意调查 2 ,那么结果应为:

  • age_1 [13-19] = 0
  • age_2 [20-29] = 3
  • age_3 [30-39] = 1
  • age_4 [40-49] = 0
  • age_5 [50+] = 0

...而是我得到了这个:

  • age_2 [20-29] = 3
  • age_3 [30-39] = 1

所以,我需要的是所有年龄段都出现在结果中,即使没有匹配也是如此。这是我目前的查询:

SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range

以下是带有示例数据的SQL Fiddle。谢谢!

1 个答案:

答案 0 :(得分:1)

我使用左连接与您的总计和合并。

select totals.age_range, coalesce(ages.q,0) total from 
( 
    select 'age_1' age_range 
    union select 'age_2' age_range 
    union select 'age_3' age_range 
    union select 'age_4' age_range 
    union select 'age_5' age_range ) totals 
left join (
  SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range
  ) ages
on totals.age_range = ages.age_range

- 结果

age_range总计

age_1 0

age_2 3

age_3 1

age_4 0

age_5 0