MySQL CASE那么空案例值

时间:2013-11-13 17:08:06

标签: mysql sql case

    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

这是我的查询。这些是结果: enter image description here

但是,如果table.age在一个类别中没有至少1个年龄,那么它将在结果中忽略该情况。像这样: enter image description here

这个数据集没有任何年龄记录&lt;因此,年龄段“&lt; 18”没有出现。我怎样才能使它显示并返回一个值0 ??

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分: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

答案 2 :(得分: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;