如何在MySQL查询中对年龄范围进行GROUP BY

时间:2013-11-26 04:58:58

标签: mysql

我有一个名为“age”的列表。我试图选择一系列年龄,然后按这些范围分组。这是我到目前为止所得到的,但无法让它发挥作用:

select t.age as [range], count(*) as [occurences]
from (
select age,
   case when age >= 0 and age < 10 then '0-9'
   when age >= 10 and age < 20 then '10-19'
   when age >= 20 and age < 20 then '20-29'
   when age >= 30 and age < 40 then '30-39'
   else '40+' end as range
from t) t
group by t.age

完成我想要做的事情的最简单方法是什么?在我的案例中,“年龄”栏目在“联系”表中。

2 个答案:

答案 0 :(得分:2)

工作正常,只有一些变化。 (这是an SQLFiddle to prove it。)

select t.range, count(*) as `occurences`
from (
select age,
   case when age >= 0 and age < 10 then '0-9'
   when age >= 10 and age < 20 then '10-19'
   when age >= 20 and age < 20 then '20-29'
   when age >= 30 and age < 40 then '30-39'
   else '40+' end as `range`
from t) as t
group by t.range
  1. MySQL使用`ident` quoting by default(和RANGE is a reserved word因此需要引用),并且;
  2. GROUP BY需要超过t.range(而不是t.age)才有意义。同样,select子句应该选择范围。
  3. 虽然我建议选择不同的别名,但在重新使用“t”时它会解析/执行。

答案 1 :(得分:1)

这应该返回您描述的结果集:

SELECT CASE WHEN t.age >= 0  AND t.age < 10 THEN '0-9'
            WHEN t.age >= 10 AND t.age < 20 THEN '10-19'
            WHEN t.age >= 20 AND t.age < 30 THEN '20-29'
            WHEN t.age >= 30 AND t.age < 40 THEN '30-39'
            ELSE '40+'
       END AS `range`
     , COUNT(*) AS `occurrences`
  FROM t
 GROUP BY `range`

为了提高性能,您希望避免使用内联视图。

如果您确实希望花费资源来遍历表并实现派生表,那么这也将返回相同的结果:

SELECT v.range
     , COUNT(*) AS `occurrences`
  FROM ( SELECT CASE WHEN t.age >= 0  AND t.age < 10 THEN '0-9'
                     WHEN t.age >= 10 AND t.age < 20 THEN '10-19'
                     WHEN t.age >= 20 AND t.age < 30 THEN '20-29'
                     WHEN t.age >= 30 AND t.age < 40 THEN '30-39'
                     ELSE '40+'
                END AS `range`
               FROM t
       ) v
 GROUP BY v.`range`