MySQL CASE WHEN THEN empty case values

你说的曾经没有我的故事 提交于 2019-12-12 10:54:21

问题


    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

This is my query. These are the results:

However if the table.age doesn't have at least 1 age in a category, it will just flat out ignore that case in the result. Like such:

This data set didnt have any records for age < 18. So the ageband "<18" doesnt show up. How can I make it so it does show up and return a value 0??


回答1:


You need a table of agebands to populate the result for entries that have no matching rows. This can be done through an actual table, or dynamically generated with a subquery like this:

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

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




回答2:


I haven't tested it, but this should work.

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



回答3:


Assuming a table AgeCat that contains your categories.

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;


来源:https://stackoverflow.com/questions/19960020/mysql-case-when-then-empty-case-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!