[英]Sum columns from two relatable tables and group by another column (postgresql)
給定兩個表:
...什么查詢可以按地區匯總師生人數?
樣本數據:
Teachers
ID, school_id
1, 1
2, 1
3, 2
4, 3
Schools
ID, student_population, district
1, 45, Falaba
2, 23, Falaba
3, 87, Bonth
4, 10, Moyamba
預期結果:
teachers, students, district
3, 68, Falaba
1, 87, Bonth
0, 10, Moyamba
我的第一次嘗試是:
select count(*) as teachers, sum(student_population), district from teachers join schools on teachers.school_id = schools.id group by district.
...然而,這個查詢導致每個學校的 student_population 被分解為屬於它的每個老師。 因此,法拉巴的學生總數為 113 (45+45+23) 而不是 68。
假設表teachers
有(至少)包含老師的id的第二列,你可以這樣做:
select
count(distinct t.teacher_id) teachers
sum(s.student_population) students,
s.district
from schools s
inner join teachers t on t.school_id = s.id
group by s.district
更好的選擇是預先聚合teachers
表:
select
sum(t.teachers) teachers,
sum(s.student_population) students,
s.district
from schools s
inner join (select school_id, count(*) teachers from teachers group by school_id) t
on t.school_id = s.id
group by s.district
teachers | students | district -------: | -------: | :------- 1 | 87 | Bonth 3 | 68 | Falaba
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.