有这个查询:
SELECT
count(*) as Total,
SUM(CASE WHEN gender = 1 then 1 ELSE 0 END) Male,
SUM(CASE WHEN gender = 2 then 1 ELSE 0 END) Female,
SUM(CASE WHEN gender = 0 then 1 ELSE 0 END) Unknown,
CASE
WHEN age>2 AND age<15 THEN '2-15'
WHEN age>18 AND age<25 THEN '18-25'
END AS var
FROM
persons
WHERE
1=1
AND `date` > '2012-01-10'
AND `date` < '2013-01-07'
GROUP BY
CASE
WHEN age>2 AND age<15 THEN '2-15'
WHEN age>18 AND age<25 THEN '18-25'
END
结果是:
Total Male Female Unknown var
29 17 12 0 NULL
7 0 7 0 18-25
3 0 3 0 2-15
第一个问题:
为什么这会导致NULL?可以做什么只显示带有值的结果?
第二个问题:
mysql在2-15之前用18-25命令我的var
列,migth是因为数字1首先出现然后是数字2.但是point是数字的顺序,然后是18,然后是18。
干杯:)
答案 0 :(得分:2)
这是因为所有CASE
表达式都有(隐含的,默认的)ELSE NULL
部分。因此,age
或age>2 AND age<15
条件未捕获的任何age>18 AND age<25
值都会导致NULL
值被分组。
解决方案是在WHERE
子句中添加一个限制:
WHERE 1=1
AND `date` > '2012-01-10' AND `date` < '2013-01-07'
AND ( (age>2 AND age<15) OR (age>18 AND age<25) ) -- this
对于第二个问题,您可以使用age
上的函数来避免在var
(字符串)上进行比较:
ORDER BY MIN(age)
或只是:
ORDER BY age
以上都不是SQL标准,但在默认的非ANSI设置下,它可以在MySQL中运行。如果您希望获得本书的100%,则可以略微更改var
:
SELECT count(*) as Total,
SUM(CASE WHEN gender = 1 then 1 ELSE 0 END) Male,
SUM(CASE WHEN gender = 2 then 1 ELSE 0 END) Female,
SUM(CASE WHEN gender = 0 then 1 ELSE 0 END) Unknown,
CASE
WHEN age>2 AND age<15 THEN '02-15' -- this was changed
WHEN age>18 AND age<25 THEN '18-25'
END AS var
FROM persons
WHERE 1=1
AND `date` > '2012-01-10' AND `date` < '2013-01-07'
AND ( (age>2 AND age<15) OR (age>18 AND age<25) )
GROUP BY
CASE
WHEN age>2 AND age<15 THEN '02-15'
WHEN age>18 AND age<25 THEN '18-25'
END
ORDER BY var ;
答案 1 :(得分:2)
第一个回答:
它为NULL,因为它不满足该年龄的任何CASE条件。像这样添加一个子句应该这样做:
WHERE (age > 2 AND age < 15) OR (age > 18 AND age < 25)
第二个回答:
你是对的,它是用字符串排序的(因为它们就是这样)。只需按ORDER ASC
或ORDER DESC
答案 2 :(得分:1)
您将获得NULL
因为它不符合您的CASE
CASE
WHEN age>2 AND age<15 THEN '2-15' // U HAVE BETWEEN 2-15
WHEN age>18 AND age<25 THEN '18-25' // u have between 18-25
// but u dont have between 15-18
//and u get null because your value is between 15-18
所以尝试在该范围内添加其他案例。
第二个问题,因为它们是字符串,而不是数字。
尝试按年龄排序