sql - 为每组数据聚合一组结果
问题描述
我有一份国家名单。每个简短的缩写(short)对应于 1 个国家,但是人们喜欢输入除国家名称之外的其他变量,这些变量以下面的列表结尾
输出
short nation Students
A A 604
A Austria 6707
A Österreich 3400
AFG Afg 18
AFG Afghanistan 1991
AGL Angola 16
AGN Guinea 2
AL Al 5
AL Albanien 61
ARM Arm 6
ARM Armenien 87
如您所见,计算每个国家/地区的学生总数可以得出 2 或 3 个结果。所以很明显我想到了这个问题,如果可以计算每个分组的短文本的总和,例如以下
预期产出
short nation Students
A A 604
A Austria 6707
A Österreich 3400
A 10711
AFG Afg 18
AFG Afghanistan 1991
AFG 2009
AGL Angola 16
AGN Guinea 2
AL Al 5
AL Albanien 61
AL 66
ARM Arm 6
ARM Armenien 87
ARM 93
我的代码如下
第1部分
with natctf as (
SELECT short,
nation,
cast(Studentcount as varchar(6)) as Studentcount
FROM (
SELECT ctf.shorttext as short, ctf.longtext as nation,
count(distinct s.studentid) as Studentcount
from students s
join pupil p on p.id = s.pupilid
join pupilnation pn on pn.pupilid = p.id
join country ctf on ctf.id = pn.coutnryid
Group by ctf.shorttext,ctf.longtext
Order by ctf.shorttext
) t )
第2部分
SELECT short, initcap(nation), Studentcount
FROM natctf
UNION ALL
SELECT null as short,
cast(count(nation) as varchar(3)) ||' Nations',
cast(SUM(cast(Studentcount as bigint)) as varchar(10)) ||' Students'
FROM natctf
解决方案
最好的解决方案是使用分组集,这是一种 SQL 标准功能,非常适合您的用例:
SELECT ctf.shorttext as short,
ctf.longtext as nation,
count(...)
FROM country AS ctf JOIN ...
GROUP BY GROUPING SETS ((ctf.shorttext, ctf.longtext), (ctf.shorttext))
ORDER BY ctf.shorttext, ctf.longtext
推荐阅读
- r - 使用 betareg 时“由 optim 提供的非有限值”
- html - 在徽标旁边设置图像
- java - java中如何处理String args[]中的逗号
- javascript - 如何使用令牌注册-MERN-通过邮件激活帐户?
- task - 什么时候可以将任务从阻塞状态切换到暂停状态?
- logic - 坚持寻找这个程序的逻辑
- java - 将本地 Maven 项目解析为 Jenkins 中的依赖项
- laravel - 为什么我的 Laravel 路由在 Laravel 7 中有效,但在 Laravel 8 中无效?
- pdf - 没有 pdf.js 或任何其他外部模块的电子应用程序中的自定义 pdf 查看器?
- javascript - 音频未按预期播放