如何使用 pivot table

How to use use pivot table

我正在尝试使用数据透视函数显示我的数据库 table 中的结果,但它没有显示我需要的结果。我的数据库中的列如下:

ScoreID, PupilID, Subject, Year, Score

我想像这样显示一个枢轴 table:

ScoreID, PupilID, Subject, Year1, Year2, Year3, Year4

我使用的SQL语句如下:

SELECT *
FROM Scores
PIVOT(SUM(Score) 
  FOR Year IN (
  [Year1],[Year2], [Year3], [Year4]
  )) AS PVTTable
  Where (PupilID = 10016) 

但是,这会为每一年的分数生成一个单独的行。所以我最后一行是英语一年级的分数,另一行是英语二年级的分数,等等。我只想为每个科目显示一行,并在该行的列中显示分数。

在此先感谢您提供的任何帮助。

试试这个:

SELECT PupilID, Subject, [Year1], [Year2], [Year3], [Year4]
FROM (
    SELECT PupilID, Subject, Year, Score
    FROM Scores
    --Where (PupilID = 10016) 
    ) AS DT
PIVOT(SUM(Score) FOR Year IN ([Year1],[Year2], [Year3], [Year4])) AS PVT

更多信息,请参阅:
https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
https://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/
http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query