1

有这个查询:

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 ?怎么做才能只显示带有值的结果?

第二个问题:
mysqlvar在 2-15 之前用 18-25 对我的列进行排序,可能是因为数字 1 先于数字 2。但关键是作为数字的顺序,然后 2 先于 18。

干杯:)

4

3 回答 3

2

这是因为所有CASE表达式都有一个(隐含的,默认的)ELSE NULL部分。因此,任何age未被 theage>2 AND age<15age>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 

对于第二个问题,您可以使用 on 函数age来避免对var(字符串)进行比较:

 ORDER BY MIN(age)

要不就:

ORDER BY age 

以上都不是 SQL 标准,但它在 MySQL 中工作,在默认的非 ANSI 设置下。如果你想 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 ;
于 2013-01-07T19:06:57.423 回答
2

第一个答案
它是NULL,因为它不满足您的任何年龄条件。像这样向 WHERE 添加一个子句应该这样做:

WHERE (age > 2 AND age < 15) OR (age > 18 AND age < 25)

第二个答案
你是对的,它是按字符串排序的(因为它们就是这样)。ORDER ASC只需通过执行或更改排序的方向ORDER DESC

于 2013-01-07T19:07:06.560 回答
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 

所以尝试在该范围内添加其他案例。

第二个问题,因为它们是字符串,而不是数字。

尝试按年龄排序

于 2013-01-07T20:17:32.647 回答