一尘不染

MySQL CASE THEHEN THEN时为空

sql

    SELECT CASE WHEN age IS NULL THEN 'Unspecified' 
                WHEN age < 18 THEN '<18' 
                WHEN age >= 18 AND age <= 24 THEN '18-24' 
                WHEN age >= 25 AND age <= 30 THEN '25-30' 
                WHEN age >= 31 AND age <= 40 THEN '31-40' 
                WHEN age > 40 THEN '>40' 
            END AS ageband, 
            COUNT(*) 
       FROM (SELECT age 
               FROM table) t 
   GROUP BY ageband

这是我的查询。结果如下: 在此处输入图片说明

但是,如果table.age在一个类别中没有至少1个年龄,则它将忽略结果中的该情况。像这样:
在此处输入图片说明

该数据集没有年龄<18的任何记录。因此年龄带“ <18”没有显示。我怎样才能使它显示并返回值0?


阅读 107

收藏
2021-05-23

共1个答案

一尘不染

您需要一个年龄表来填充没有匹配行的条目的结果。这可以通过实际表完成,也可以通过子查询动态生成,如下所示:

SELECT a.ageband, IFNULL(t.agecount, 0)
FROM (
  -- ORIGINAL QUERY
  SELECT
    CASE
      WHEN age IS NULL THEN 'Unspecified'
      WHEN age < 18 THEN '<18'
      WHEN age >= 18 AND age <= 24 THEN '18-24'
      WHEN age >= 25 AND age <= 30 THEN '25-30'
      WHEN age >= 31 AND age <= 40 THEN '31-40'
      WHEN age > 40 THEN '>40'
    END AS ageband,
    COUNT(*) as agecount
  FROM (SELECT age FROM Table1) t
  GROUP BY ageband
) t
right join (
  -- TABLE OF POSSIBLE AGEBANDS
  SELECT 'Unspecified' as ageband union
  SELECT '<18' union
  SELECT '18-24' union
  SELECT '25-30' union
  SELECT '31-40' union
  SELECT '>40'
) a on t.ageband = a.ageband

演示:http ://www.sqlfiddle.com/#!2/
7e2a9/10

2021-05-23