PostgreSQL或Rails中的部分透视

时间:2016-10-04 11:14:12

标签: sql ruby-on-rails ruby postgresql pivot-table

假设我有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 数学领域是“数学”科目的平均分数,物理领域是“物理”科目的平均分数,化学领域是id为student_id的学生的“化学”科目的平均分数。

我知道我可以在Rails ActiveRecord::Base中处理它,但即使使用include,我最终也会使用很多查询。

如何只使用一个查询生成所需的输出?

1 个答案:

答案 0 :(得分:3)

您可以使用连接和聚合执行此操作:

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;