5
    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?

4

3 回答 3

10

您需要一个年龄范围表来填充没有匹配行的条目的结果。这可以通过一个实际的表来完成,或者使用这样的子查询动态生成:

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

于 2013-11-13T17:16:47.970 回答
1

我还没有测试过,但这应该可以。

SELECT ageband, cnt FROM (
  SELECT '<18' as ageband, COUNT(*) as cnt FROMT table WHERE age < 18
  UNION ALL
  SELECT '18-24' as ageband, COUNT(*) as cnt FROMT table WHERE age >= 18 AND age <= 24
  UNION ALL
  SELECT '25-30' as ageband, COUNT(*) as cnt FROMT table WHERE age >= 25 AND age <= 30
  UNION ALL
  SELECT '31-40' as ageband, COUNT(*) as cnt FROMT table WHERE age >= 31 AND age <= 40
  UNION ALL
  SELECT '>40' as ageband, COUNT(*) as cnt FROMT table WHERE age > 40
) as A
于 2013-11-13T17:20:00.633 回答
0

假设一个表 AgeCat 包含您的类别。

SELECT c.Cat, COUNT(*) FROM Age a
RIGHT JOIN AgeCat c ON (
(a.age < 18 AND c.Cat = '<18')
OR (a.age BETWEEN 18 AND 24 AND c.Cat = '18-24')
OR (a.age BETWEEN 26 AND 30 AND c.Cat = '25-30')
-- etc.
) GROUP BY c.Cat;
于 2013-11-13T17:16:41.100 回答