如何将三个表与其他两个返回的多个值行连接起来
How to Join three tables with multiple values rows returned on the other two
举个例子。
我有三个独立的 tables:
course
Table 具有 CourseId、StudentId 等
student
当然包含学生数据和 StudentName
score
table
我只想要每个 table 中的一列并将它们融合为一列。
CourseId StudentName Scores
---------- ------------- ----------
1 Gashio 10
1 Gashio 20
1 Lee 35
1 Lee 40
1 Edith 5
2 Lana 3
2 Reisha 50
每门课程都有多个学生,每个分数都有他们在一个月的课程中获得的多个分数。
结果我想要这样的东西:
CourseId StudentName Scores
--------- ------------- -------------
1 Gashio 10|20
1 Lee 35|40
1 Edith 5
2 Lana 3
2 Reisha 50
由于分数 return 多个值,我希望它成为一个由分隔符分隔的列。
我不确定这是否是我应该使用的地方 STRING_AGG?
您需要 STRING_AGG
和 GROUP BY
SELECT course.CourseId,
student.StudentName,
STRING_AGG(Scores, ,'|') AS Scores
FROM course INNER JOIN
student ON student.StudentId = course.StudentId INNER JOIN
score ON score.studentId = student.StudentId
GROUP BY cource.CourseId,
student.StudentName
使用带分隔符的 string_agg()
select CourseId,StudentName,string_agg(Scores,'|') as scores
from tablename
group by CourseId,StudentName
举个例子。
我有三个独立的 tables:
course
Table 具有 CourseId、StudentId 等student
当然包含学生数据和 StudentNamescore
table
我只想要每个 table 中的一列并将它们融合为一列。
CourseId StudentName Scores
---------- ------------- ----------
1 Gashio 10
1 Gashio 20
1 Lee 35
1 Lee 40
1 Edith 5
2 Lana 3
2 Reisha 50
每门课程都有多个学生,每个分数都有他们在一个月的课程中获得的多个分数。
结果我想要这样的东西:
CourseId StudentName Scores
--------- ------------- -------------
1 Gashio 10|20
1 Lee 35|40
1 Edith 5
2 Lana 3
2 Reisha 50
由于分数 return 多个值,我希望它成为一个由分隔符分隔的列。
我不确定这是否是我应该使用的地方 STRING_AGG?
您需要 STRING_AGG
和 GROUP BY
SELECT course.CourseId,
student.StudentName,
STRING_AGG(Scores, ,'|') AS Scores
FROM course INNER JOIN
student ON student.StudentId = course.StudentId INNER JOIN
score ON score.studentId = student.StudentId
GROUP BY cource.CourseId,
student.StudentName
使用带分隔符的 string_agg()
select CourseId,StudentName,string_agg(Scores,'|') as scores
from tablename
group by CourseId,StudentName