gpt4 book ai didi

sql - PostgreSQL 或 Rails 中的部分透视

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:40 24 4
gpt4 key购买 nike

假设我有 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

另外,假设字符串枚举总是正确的,只填充这三个可能值中的一个。

我需要这样的结果查询
学生编号 |学生姓名 |类名 |数学 |物理学 |化学
其中math field是id为student_id的学生“Math”科目的平均分,physics field是“Physics”科目的平均分数,chemistry field是“Chemistry”科目的平均分数。

我知道我可以在 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;

关于sql - PostgreSQL 或 Rails 中的部分透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com