sql - 如何在 postgres 列中对顶级类别进行排名
问题描述
我需要找到一所学校的前 5 个民族。
Select count(distinct studentnr),
count(case when ctf.text like 'United Kingdom' then 1 end) as nation1,
count(case when ctf.text like 'Germany' then 1 end) as nation2,
count(case when ctf.text like 'France' then 1 end) as nation3,
count(case when ctf.text like 'Italy' then 1 end) as nation4,
count(case when ctf.text like 'Hungary' then 1 end) as nation5
from student s
join pupil p on p.id = s.personid
join pupilnationality pn on pn.pupilid = p.id
join country ctf on ctf.id = pn.countryid
如您所见,这是手动搜索,我希望查找字段并进行计数并将它们单独分类在一个列中。
但是我只想要前 5 名 这几乎是我想要的 这需要分区或排名吗?
解决方案
为什么不将它们放在单独的行中?
select ctf.text, count(*)
from student s join
pupil p
on p.id = s.personid join
pupilnationality pn
on pn.pupilid = p.id join
country ctf
on ctf.id = pn.countryid
group by ctf.text
order by count(*) desc
limit 5;
推荐阅读
- sql - 在postgresql数据库中查找今年加入的所有用户
- .net-core - 如何获取 CSharpCompilation 的 System.Collections 参考
- python - 了解使用生成器进行数据管道的程序的程序流程和代码
- c# - VS 解决方案调试源文件设置位置?
- python - 调用多个子进程命令并在子进程完成时重新启动任何命令
- javascript - 上传时出现 Codecov 问题
- vba - VBA Excel忽略PrintArea Pdf
- javascript - 我如何使用 javascript 显示超过 1 个项目
- mysql - 如何在 laravel 中最大化行大小 | mysql
- postgresql - INSERT ON DUPLICATE 语句返回什么?