如何使用数据透视表

时间:2015-02-12 22:10:08

标签: sql sql-server pivot

我正在尝试使用数据透视表功能显示数据库表中的结果,但它并没有按照我的需要显示它们。我的数据库中的列如下:

ScoreID, PupilID, Subject, Year, Score

我想显示一个像这样的数据透视表:

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) 

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

提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

试试这个:

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