如何在SQL查询中将列显示为行?

时间:2016-11-15 09:33:05

标签: sql sql-server

我正在尝试在包含两个表tblStudentstblExamResults的简单数据库中显示考试结果。

tblstudents包含学生ID和Full_Name列

tblexamResults列中有Student_id,Subject和Marks。

如下图所示

tblstudents

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 - 结果如下图所示:

enter image description here

3 - 但我想要的是将每个主题显示为行并获得其下每个主题的结果

这样每个学生的结果都显示在同一行:

Student_Name sub1_result sub2_Result sub3_Result

如下图所示(Excel截图)

enter image description here

所以:

  • 如何以该格式显示数据?
  • 在SQL Server中可以吗?

2 个答案:

答案 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

中的括号,我在第5行遇到错误
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)