sql - 具有不同计数的 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
解决方案
我建议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)
推荐阅读
- php - Laravel View 不适合 dompdf 生成的 pdf
- wordpress - 如果条件正确,wordpress
- node.js - 我们如何从 CF 中托管的 NodeJS 应用程序访问外部 .CSV 文件
- wordpress - 声音按钮视频 Flatsome
- c++ - 出于什么原因,像 std::sort() 这样的函数会直接更改向量而不是返回值?
- flutter - 我如何解决颤振的火力基地身份验证
- android - 使用 Firebase 在应用程序 Android Studio 中复制消息
- sql-server - Tsql:取消长时间运行的更改表的问题?
- sql - 向 SQL 选择添加细分维度
- android - 在Activity上线之前,不能在Android的应用范围内隐藏statusBar