簡體   English   中英

對兩個相關表中的列求和並按另一列分組(postgresql)

[英]Sum columns from two relatable tables and group by another column (postgresql)

給定兩個表:

  • 教師:ID,school_id
  • 學校:ID、student_population、地區。

...什么查詢可以按地區匯總師生人數?

樣本數據:

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

DB Fiddle 上的演示

teachers | students | district
-------: | -------: | :-------
       1 |       87 | Bonth   
       3 |       68 | Falaba

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM