首页 > 解决方案 > 具有不同计数的 SQLGroup

问题描述

我有疑问

select count(distinct(a.studentid)count,
    case
      when a.Age <=19 then '1-19'
      when a.Age between 20 and 29 then '20-29'
    end as age_range
from table a 
where 0 = 0
group by a.age

结果

count  age_range
 10      1-19
  5      1-19
 12      20-29
 18      20-29

不知道为什么不按范围分组并期待结果。谢谢你。

 count   age_range
 15       1-19
 30       20-29

标签: sqlsql-server

解决方案


我建议cross apply定义别名:

select v.age_range, count(distinct a.studentid)count,
from table a cross apply
     (values (case when a.Age <= 19 then 'Under 12 months-19'
                   when a.Age between 20 and 29 then '20-29'
              end)
     ) as v(age_range)
group by v.age_range;

SQL Server 不允许别名作为GROUP BY键。我认为在FROM子句中定义别​​名是最简单的方法;您还可以使用 CTE 或子查询或重复case表达式。

between我还应该注意case. 这些子句按顺序进行评估,因此您可以使用:

(case when a.Age <= 19 then 'Under 12 months-19'
      when a.Age <= 29 then '20-29'
 end)

推荐阅读