是否可以为MySQL查询定制GROUP BY?

时间:2013-11-26 06:41:05

标签: mysql group-by

我一直在尝试找到在查询中对两个年龄段进行分组的最简单方法。这样的事情有可能奏效吗?

SELECT age,
sum(case when age < '20' then 1 else 0 end),
sum(case when age > '20' then 1 else 0 end)
FROM Contact
GROUP BY ...."custom group one"......"custom group one".....??

我知道你应该通常在一个专栏上分组,但在我的情况下,我不起作用。有什么建议? THX!

Table:            Desired Query Result:
Name    Age       0           1
John    18        Under 20    2
Harry   22        Over 20     2
Mary    17
Megan   27

解决:

SELECT CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                          
  ELSE 'old'
END, Count(id)
FROM  Contact
GROUP BY CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                       
  ELSE 'old'
END

注意:AS可用于为SELECT语句中的分组条件指定别名,因此避免重复两次条件,即

SELECT CASE
  WHEN age = '21' THEN 'young'
  WHEN  age BETWEEN '22' AND '60' THEN 'middle'                          
  ELSE 'old'
END AS age_range, Count(id)
FROM  Contact
GROUP BY age_range

1 个答案:

答案 0 :(得分:1)

那将是:

SELECT 
  COUNT(1), 
  age>20 AS Above20 
FROM t 
GROUP BY age>20

- 检查此fiddle

或者,使用SUM()和列视图:

SELECT
  SUM(IF(age>20, 1, 0)) AS Above20,
  SUM(IF(age<=20, 1, 0)) AS Below20
FROM 
  t

- 检查此fiddle