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个年龄,则它将忽略结果中的该情况。像这样:

该数据集没有年龄

最佳答案

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

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

关于MySQL CASE THEHEN THEN时为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19960020/

10-09 07:08