行转列操作,主要用到了Pivot
Pivot语法结构:
Pivot (A) for B in(C)
A:Max(Total),表示要显示的合计值,
B:Monthly,原始数据的列头,就是要把它的数据转化为列的字段的名字
C:动态列 B的数据内容
数据表脚本如下:
CREATE TABLE [dbo].[StudentScore](
[UserNo] [varchar](50) NOT NULL,
[UserName] [varchar](50) NOT NULL,
[Course] [varchar](60) NOT NULL,
[Score] [int] NOT NULL
) ON [PRIMARY]
INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'001', N'张三', N'语文', 90)
INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'001', N'张三', N'数学', 85) INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'001', N'张三', N'英文', 88) INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'002', N'李四', N'英文', 60) INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'002', N'李四', N'语文', 99) INSERT [dbo].[StudentScore] ([UserNo], [UserName], [Course], [Score]) VALUES (N'002', N'李四', N'数学', 100)
行转列脚本如下:
DECLARE @Course VARCHAR(400), @SQL VARCHAR(4000) --获取课程列 SELECT @Course = ISNULL(@Course+',','')+ QUOTENAME([Course]) FROM StudentScore GROUP BY Course --行转列 SET @SQL = 'SELECT * FROM StudentScore PIVOT(SUM([Score]) FOR Course IN('+@Course+'))A ORDER BY A.UserNo' EXEC(@SQL) --行转列并增加汇总 SET @SQL = 'SELECT UserNo,UserName,'+@Course+',[总成绩] FROM (SELECT *,[总成绩]=SUM(Score) OVER (partition by UserNo) FROM StudentScore) A PIVOT (MAX(Score) FOR [Course] IN('+@Course+'))B' EXEC(@sql)