【问题标题】:How to rank top categories in a column postgres如何在 postgres 列中对顶级类别进行排名
【发布时间】:2018-09-12 12:34:10
【问题描述】:

我需要找出学校中排名前 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 名 这几乎是我想要的 这需要分区或排名吗?

【问题讨论】:

    标签: sql postgresql postgresql-9.3 rank


    【解决方案1】:

    为什么不把它们放在不同的行中?

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多