Как ранжировать верхние категории в столбце postgres - PullRequest
0 голосов
/ 12 сентября 2018

Мне нужно найти 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 Вот что я хочу. Требуется ли раздел или ранг?

enter image description here

1 Ответ

0 голосов
/ 12 сентября 2018

Почему бы не поместить их в отдельные строки?

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;
...