在sql中按别名分组

xbp102n0  于 2021-07-29  发布在  Java
关注(0)|答案(5)|浏览(420)

我也见过其他化名分组的例子。然而,我似乎不能使它为我的例子工作。
我有一个表与人的信息,我想分组的年龄类别(20-25、26-30、31-35、36-40和>40)

到目前为止我管理的代码是:

select sub  
from   (    
  select  Case 
            when Age <26 then'20-26' 
            when Age <31 then '26-30'    
            when Age < 36 then '31-35'    
            when Age <41 then '36-40'    
            else '>40' 
          end    
  from people
) as sub
Group by sub

我想得到每个年龄组的总人数。

nfzehxib

nfzehxib1#

使用cte生成范围,然后在该cte上聚合:

WITH cte AS (
    SELECT CASE Age WHEN < 26 THEN '20-26'
                    WHEN < 32 THEN '26-30'
                    WHEN < 36 THEN '31-35'
                    WHEN < 41 THEN '36-40'
                    ELSE '> 40' END AS age_group
    FROM people
)

SELECT age_group, COUNT(*)
FROM cte
GROUP BY age_group;

请注意,在其他一些数据库供应商(如mysql和sqlite)上,您实际上可以 GROUP BY 在同一查询的select中定义的别名,因此在这种情况下甚至不需要正式的cte/子查询。

mgdq6dx1

mgdq6dx12#

请使用下面的查询,

select age_category, count(1) from
(select 
case when Age between 0 and 25 then '20-25'
     when Age between 26 and 30 then '26-30'
     when Age between 31 and 35 then '31-35'     
     when Age between 36 and 40 then '36-40'
     else '>40' end as age_category
from people) qry group by age_category;
lyr7nygr

lyr7nygr3#

你可以用 case 直接在 group by 条款。

select
  case
    when Age < 26 then '20-26'
    when Age < 31 then '26-30'
    when Age < 36 then '31-35'
    when Age < 41 then '36-40'
    else '>40'
  end as age_cat,
  count(*)
from people
group by
  case
    when Age < 26 then '20-26'
    when Age < 31 then '26-30'
    when Age < 36 then '31-35'
    when Age < 41 then '36-40'
    else '>40'
  end;

或者,可以计算值​​对于 group by 合同条款 cross apply 接线员。

select
  ca.age_cat,
  count(*)
from people
cross apply(
  select
    case
      when Age < 26 then '20-26'
      when Age < 31 then '26-30'
      when Age < 36 then '31-35'
      when Age < 41 then '36-40'
      else '>40'
    end as age_cat
) as ca
group by ca.age_cat;

演示。

9wbgstp7

9wbgstp74#

如果希望结果集包含零人的组,我建议使用派生表方法:

with age_groups as (
      select *
      from (values (0, 26, '20-26'),
                   (26, 31, '26-30'),  
                   (31, 36, '31-35'),  
                   (36, 41, '36-40')   
                   (41, null, '>40')
           ) v(min_age, max_age, grp) 
      )
select ag.grp, count(p.age)  
from age_groups ag left join
     people p
     on p.age >= ag.min_age and (p.age < ag.max_age or ag.max_age is null)
group by ag.grp
order by min(ag.min_age);
k3bvogb1

k3bvogb15#

谢谢大家的帮助。我用了下面的,它的工作!!!

select t.agecat as[age_range],count(*) as [Number of People]
from (
select case
when age <26 then '20-25'
when age <31 then '26-30'
when age <36 then '31-35'
when age<41 then '36-40'
else '>40' end as agecat
from people) t
group by t.agecat

相关问题