gpt4 book ai didi

MySQL CASE WHEN THEN 空大小写值

转载 作者:可可西里 更新时间:2023-11-01 07:00:21 27 4
gpt4 key购买 nike

    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

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

最佳答案

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

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 WHEN THEN 空大小写值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960020/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com