简体   繁体   English

PostgreSQL或Rails中的部分透视

[英]Partial Pivoting in PostgreSQL or Rails

Assume I have 3 tables, and I can't change any DDL 假设我有3个表,并且我不能更改任何DDL

Class
id: integer
name: string

and

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

and

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

Also, assume that the string enum will always correct, filled by only one of those three possible values. 此外,假设字符串枚举将始终正确,仅由这三个可能值之一填充。

And I need a resulting query like this 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 student_id | student_name | class_name | math | physics | chemistry where math field is the average score of "Math" subject, physics field is the average score of "Physics" subject, and chemistry field is the average score of "Chemistry" subject of the student with id student_id. student_id | student_name | class_name | math | physics | chemistry ,其中数学字段是ID为“ student_id”的学生的平均分数,“物理”字段是“物理”主题的平均分数,“化学”字段是“ id”学生的平均分数。

I know that I can handle it in Rails ActiveRecord::Base , but even using include, I end up with using many queries. 我知道我可以在Rails ActiveRecord::Base处理它,但是即使使用include,我最终也会使用许多查询。

How can I generate that needed output with using only one query? 如何仅使用一个查询生成所需的输出?

You can do this with joins and aggregation: 您可以通过联接和聚合来实现:

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