我正在尝试转换长数据:
ID|SchoolID|Section|RepScore|SportsScore|PartyScore
1 |20 |1 |23.2 |70.2 |42.3
2 |20 |6 |65.2 |75.8 |52.3
3 |20 |7 |77.2 |72.2 |66.3
4 |21 |10 |13.2 |40.2 |72.3
5 |21 |11 |25.2 |55.8 |72.3
6 |21 |12 |37.2 |62.2 |76.3
到宽数据(我只使用前三行来保持简短):
SchoolID|RpScr1|RpScr6|RpScr7|SprtScr1|SprtScr6|SprtScr7|Prty1|Prty6|Prty7
20 |23.2 |65.2 |77.2 |70.2 |75.8 |72.2 |42.3 |52.3 |66.3
我试过这个:
DECLARE @cols VARCHAR(1000)
DECLARE @cols2 VARCHAR(1000)
DECLARE @cols3 VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
SELECT @cols = STUFF(( SELECT distinct '], [a' + cast([Section] as varchar)
FROM [dbo].[SchoolData] FOR XML PATH('') ), 1, 2, '') + ']'
SELECT @cols2 = STUFF(( SELECT distinct '], [b' + cast([Section] as varchar)
FROM [dbo].[SchoolData] FOR XML PATH('') ), 1, 2, '') + ']'
SELECT @cols3 = STUFF(( SELECT distinct '], [c' + cast([Section] as varchar)
FROM [dbo].[SchoolData] FOR XML PATH('') ), 1, 2, '') + ']'
SET @sqlquery = 'SELECT * FROM
(SELECT z.Section,z.RepScore,z.SportsScore,z.PartyScore
FROM [dbo].[SchoolData] z) base
PIVOT (Max(RepScore) FOR [Section] IN (' + @cols + ')) AS finalpivot
PIVOT (Max(SportsScore) FOR [Section] IN (' + @cols + ')) AS finalpivot2
PIVOT (Max(PartyScore) FOR [Section] IN (' + @cols + ')) AS finalpivot3'
EXECUTE ( @sqlquery )
这是我得到的错误:Msg 8114, Level 16, State 1, Line 7 将数据类型 nvarchar 转换为 int 时出错。消息 473,级别 16,状态 1,第 7 行 PIVOT 运算符中提供了不正确的值“a9”。消息 207,级别 16,状态 1,第 8 行 列名“部分”无效。
当我尝试这样的一个时:
DECLARE @cols VARCHAR(1000)
DECLARE @sqlquery VARCHAR(2000)
SELECT @cols = STUFF(( SELECT distinct '], [a' + cast([Section] as varchar)
FROM [dbo].[SchoolData] FOR XML PATH('') ), 1, 2, '') + ']'
SET @sqlquery = 'SELECT * FROM
(SELECT z.Section,z.RepScore,z.SportsScore,z.PartyScore
FROM [dbo].[SchoolData] z) base
PIVOT (Max(RepScore) FOR [Section] IN (' + @cols + ')) AS finalpivot'
它仅适用于一列,并给出类似 [1]、[6]、[7] 的列名称。但它不适用于我需要的多个列。有任何想法吗?
你在找这个吗
如果您已经知道 Section + score 类型的所有可能值,您可以尝试以下枢轴/反枢轴技巧:
这就是我最终做到的方式。