我有UserExams表,如下所示
我需要显示FirstName, First, Second, Final
我尝试过使用PIVOT,但聚合功能不会返回所有StudentMarks
select *
from
(
SELECT Users.FirstName,
ExamsNames.Name,
UserExams.StudentMark
FROM Exams INNER JOIN ExamsNames ON Exams.ExamNameID = ExamsNames.ExamsNamesID
INNER JOIN UserExams ON Exams.ExamID = UserExams.ExamID
INNER JOIN Users ON UserExams.UserID = Users.UserID
)t
PIVOT
(
min(StudentMark)
for Name in ([First],[Second],[Final])
)p
答案 0 :(得分:1)
您当前查询的编写方式将为min(StudentMark)
中的每个考试返回一个Name
。如果您想为每个考试返回多个值,那么您需要包含另一个列,它会为您提供不同的行 - 我建议使用row_number
:
select FirstName, [First],[Second],[Final]
from
(
SELECT Users.FirstName,
ExamsNames.Name,
UserExams.StudentMark,
row_number() over(partition by Users.FirstName, ExamsNames.Name
order by UserExams.StudentMark) seq
FROM Exams
INNER JOIN ExamsNames ON Exams.ExamNameID = ExamsNames.ExamsNamesID
INNER JOIN UserExams ON Exams.ExamID = UserExams.ExamID
INNER JOIN Users ON UserExams.UserID = Users.UserID
)t
PIVOT
(
min(StudentMark)
for Name in ([First],[Second],[Final])
)p