我正在尝试在包含两个表tblStudents
和tblExamResults
的简单数据库中显示考试结果。
tblstudents
包含学生ID和Full_Name列
在tblexamResults
列中有Student_id,Subject和Marks。
如下图所示
1-目前我正在使用此查询显示学生成绩
SELECT tblStudents.Full_Name, tblExamResults.Subject, tblExamResults.Marks
FROM tblExamResults INNER JOIN
tblStudents ON tblExamResults.Student_id = tblStudents.Student_ID
order by tblStudents.Full_Name
2 - 结果如下图所示:
3 - 但我想要的是将每个主题显示为行并获得其下每个主题的结果
这样每个学生的结果都显示在同一行:
Student_Name sub1_result sub2_Result sub3_Result
如下图所示(Excel截图)
所以:
答案 0 :(得分:2)
select fullname,[english] english, [history] history, [physics] physics
from
(
select fullname,subject,marks
from (yourquery)
) src
pivot
(
max(marks)
for subject in ([english], [history], [physics])
) piv;
或
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.subject)
FROM (yourquery) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT fullname, ' + @cols + ' from
(
select fullname,subject,marks
from (your query)
) x
pivot
(
max(marks)
for subject in (' + @cols + ')
) p '
execute(@query)
fullname english history physics
a 85 70 60
i 60 100 89
s 90 90 99
答案 1 :(得分:0)
最后,我使用@Chanukya的下一部分回答了一点变化
在那个答案中,由于FROM (yourquery) c
Declare @query nvarchar(max);
DECLARE @cols AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.subject)
FROM tblExamResults c ' parentheses Removed from (tblExamResults) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
print(@cols)
set @query = '
SELECT *
FROM (
SELECT tblStudents.Full_Name, tblExamResults.Subject, tblExamResults.Marks
FROM tblExamResults INNER JOIN
tblStudents ON tblExamResults.Student_id = tblStudents.Student_ID
) as s
PIVOT
(
sum(marks) FOR subject IN ('+ @cols +')
)AS pvt'
;
execute(@query)