[英]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.