簡體   English   中英

PostgreSQL或Rails中的部分透視

[英]Partial Pivoting in PostgreSQL or Rails

假設我有3個表,並且我不能更改任何DDL

Class
id: integer
name: string

Student
id: integer
name: string
class_id: integer //Foreign key to Class table

Score
id: integer
student_id: integer //Foreign key to Student table
subject: string //String enum of "Math", "Physics", "Chemistry"
score: float

此外,假設字符串枚舉將始終正確,僅由這三個可能值之一填充。

我需要這樣的結果查詢: student_id | student_name | class_name | math | physics | chemistry student_id | student_name | class_name | math | physics | chemistry student_id | student_name | class_name | math | physics | chemistry ,其中數學字段是ID為“ student_id”的學生的平均分數,“物理”字段是“物理”主題的平均分數,“化學”字段是“ id”學生的平均分數。

我知道我可以在Rails ActiveRecord::Base處理它,但是即使使用include,我最終也會使用許多查詢。

如何僅使用一個查詢生成所需的輸出?

您可以通過聯接和聚合來實現:

select s.student_id, s.student_name, c.class_name,
       avg(case when sc.subject = 'Math' then sc.score end) as Math,
       avg(case when sc.subject = 'Physics' then sc.score end) as Physics,
       avg(case when sc.subject = 'Chemistry' then sc.score end) as Chemistry
from students s join
     scores sc 
     on sc.student_id = s.id join
     classes c
     on sc.class_id = cl.id
group by s.student_id, s.student_name, c.class_name;

暫無
暫無

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

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