您可以使用“分组依据”将人分为年龄组吗

时间:2019-12-27 12:52:25

标签: sql group-by range

我想使用group by按年龄组对这些人的列表进行分组。 例如:

  
      
  • 20多岁-7
  •   
  • 30秒-4
  •   
  •   

查询完全像这样吗?

With age as (
case 
when age < 13 then 'Under 13'
when age between 13 and 19 then 'Teens'
when age between 20 and 29 then '20s'
when age between 30 and 39 then '30s'
when age between 40 and 49 then '40s'
when age between 50 and 59 then '50s'
when age between 60 and 69 then '60s'
when age between 70 and 79 then '70s'
when age > 80 then 'Over 80'
end as AgeGroup from NameList

enter image description here

3 个答案:

答案 0 :(得分:1)

您需要CTE中的select。我想你想要

With age as (
      select nl.*,
             (case when age < 13 then 'Under 13'
                   when age between 13 and 19 then 'Teens'
                   when age between 20 and 29 then '20s'
                   when age between 30 and 39 then '30s'
                   when age between 40 and 49 then '40s'
                   when age between 50 and 59 then '50s'
                   when age between 60 and 69 then '60s'
                   when age between 70 and 79 then '70s'
                   when age > 80 then 'Over 80'
              end) as AgeGroup
      from NameList
     )
select age.agegroup, count(*)
from age
group by age.agegroup
order by min(age.age);

答案 1 :(得分:1)

尝试以下查询

With age,AgeGroup as (
select age,case 
when age < 13 then 'Under 13'
when age between 13 and 19 then 'Teens'
when age between 20 and 29 then '20s'
when age between 30 and 39 then '30s'
when age between 40 and 49 then '40s'
when age between 50 and 59 then '50s'
when age between 60 and 69 then '60s'
when age between 70 and 79 then '70s'
when age > 80 then 'Over 80'
end as AgeGroup from NameList)select * from age group by age,AgeGroup

答案 2 :(得分:1)

无需使用CTE即可获得计数的另一种方法:

    SELECT CASE WHEN age < 13               THEN 'Under 13'
                 WHEN age BETWEEN 13 AND 19 THEN 'Teens'
                 WHEN age BETWEEN 20 AND 29 THEN '20s'
                 WHEN age BETWEEN 30 AND 39 THEN '30s'
                 WHEN age BETWEEN 40 AND 49 THEN '40s'
                 WHEN age BETWEEN 50 AND 59 THEN '50s'
                 WHEN age BETWEEN 60 AND 69 THEN '60s'
                 WHEN age BETWEEN 70 AND 79 THEN '70s'
                 WHEN age > 80 THEN 'Over 80' 
                 END AS AgeGroup , COUNT(1) AS Counts
    FROM NameList
    GROUP BY CASE WHEN age < 13               THEN 'Under 13'
                   WHEN age BETWEEN 13 AND 19 THEN 'Teens'
                   WHEN age BETWEEN 20 AND 29 THEN '20s'
                   WHEN age BETWEEN 30 AND 39 THEN '30s'
                   WHEN age BETWEEN 40 AND 49 THEN '40s'
                   WHEN age BETWEEN 50 AND 59 THEN '50s'
                   WHEN age BETWEEN 60 AND 69 THEN '60s'
                   WHEN age BETWEEN 70 AND 79 THEN '70s'
                   WHEN age > 80 THEN 'Over 80' 
                   END