如何在GROUP BY CASE之后集成HAVING子句

时间:2013-11-27 02:45:00

标签: mysql

我有以下查询正常工作,但需要过滤掉状态设置为“无效”或“已存档”的记录中的年龄。我的表名为Contact,并且具有状态列和年龄列。其他状态为“活动”,“跟进”和“已完成”。

SELECT CASE
  WHEN age BETWEEN '0' AND '18' THEN '18 and Under'   
  WHEN  age BETWEEN '19' AND '30' THEN '19 to 30'   
  WHEN age BETWEEN '31' AND '40' THEN '31 to 40'   
  WHEN  age BETWEEN '41' AND '50' THEN '41 to 50'   
  WHEN age BETWEEN '51' AND '60' THEN '51 to 60'                             
  ELSE '61 and Older'
  END
 ,Count(id)
FROM  Contact
GROUP BY 
CASE
  WHEN age BETWEEN '0' AND '18' THEN '18 and Under'   
  WHEN  age BETWEEN '19' AND '30' THEN '19 to 30'   
  WHEN age BETWEEN '31' AND '40' THEN '31 to 40'   
  WHEN  age BETWEEN '41' AND '50' THEN '41 to 50'   
  WHEN age BETWEEN '51' AND '60' THEN '51 to 60'                             
  ELSE '61 and Older'
END

我正在尝试按如下方式集成HAVING子句,但不确定将其放在何处:

HAVING status NOT IN('Invalid', 'Archived')

我尝试的每个地方都会出错。任何有助于指出正确方向的帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

试试这个sqlFiddle example

SELECT CASE
        WHEN age BETWEEN  '0' AND '18' THEN '18 and Under'   
        WHEN age BETWEEN '19' AND '30' THEN '19 to 30'   
        WHEN age BETWEEN '31' AND '40' THEN '31 to 40'   
        WHEN age BETWEEN '41' AND '50' THEN '41 to 50'   
        WHEN age BETWEEN '51' AND '60' THEN '51 to 60'                             
        ELSE '61 and Older'
       END as age_range,
       status,
       Count(id) as `count`
FROM  Contact
WHERE status NOT IN ('Invalid','Archived')
GROUP BY age_range,status;

或者如果你想使用HAVING status NOT IN ('Invalid','Archived'),你可以使用下面的结果与上面相同。 (sqlfiddle example

SELECT CASE
        WHEN age BETWEEN  '0' AND '18' THEN '18 and Under'   
        WHEN age BETWEEN '19' AND '30' THEN '19 to 30'   
        WHEN age BETWEEN '31' AND '40' THEN '31 to 40'   
        WHEN age BETWEEN '41' AND '50' THEN '41 to 50'   
        WHEN age BETWEEN '51' AND '60' THEN '51 to 60'                             
        ELSE '61 and Older'
       END as age_range,
       status,
       Count(id) as `count`
FROM  Contact
GROUP BY age_range,status
HAVING status NOT IN ('Invalid','Archived');