我有一个与动态列的圆值有关的问题。
我是动态的(过去X天)创建一个每日分数的玩家列表,我想用这种格式ROUND(Score, 2)
来舍入这些分数。这是我的疑问:
DECLARE @Column AS NVARCHAR(MAX),
@SQL AS NVARCHAR(MAX)
SELECT [Player], [Start], [Average]
INTO #DbTemp1
FROM [PlayerScoreByWeek]
WHERE [Start] >= DateAdd(DAY, -7, GETDATE())
SELECT @Column = STUFF((SELECT ',' + QUOTENAME([Start])
FROM #DbTemp1
GROUP BY [Start]
ORDER BY [Start] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @SQL = 'SELECT [Player],' + @Column + '
INTO #DbTemp2
FROM
(
SELECT [Player], [Start], [Average]
FROM #DbTemp1
) AS SourceTable
PIVOT
(
AVG([Average])
FOR [Start] IN (' + @Column + ')
) AS PivotTable
ORDER BY Len([Player]), Player
SELECT * FROM #DbTemp2'
EXECUTE(@SQL)
当前输出如下:
Player 2014-02-24 2014-02-25 2014-02-26 2014-02-27 2014-02-28 2014-03-01 2014-03-02
------ ---------- ---------- ---------- ---------- ---------- ---------- ----------
Carl 26.21654 55.1542 12.29612 29.16546 32.4556 21.1485 48.3652
Gene 46.13444 29.3298 16.31642 12.86592 65.6235 52.8525 31.5915
Kim 25.69554 39.5986 32.23184 34.55685 59.2125 12.2316 29.1242
这是理想的输出:
Player 2014-02-24 2014-02-25 2014-02-26 2014-02-27 2014-02-28 2014-03-01 2014-03-02
------ ---------- ---------- ---------- ---------- ---------- ---------- ----------
Carl 26.22 55.15 12.30 29.17 32.46 21.14 48.37
Gene 46.13 29.33 16.32 12.87 65.62 52.85 31.59
Kim 25.70 39.60 32.23 34.56 59.21 12.23 29.12
鉴于列是动态创建的,因此无法在'@SQL'查询中使用round函数。 谢谢你的帮助 !
答案 0 :(得分:1)
为您的输出创建另一个变量 - 例如:
DECLARE @Column AS NVARCHAR(MAX), @Output nvarchar(max), @SQL AS NVARCHAR(MAX)
SELECT [Player], [Start], [Average] INTO #DbTemp1 FROM [PlayerScoreByWeek]
WHERE [Start] >= DateAdd(DAY, -7, GETDATE())
SELECT @Column = STUFF((SELECT ','+ QUOTENAME([Start])
FROM #DbTemp1
GROUP BY [Start]
ORDER BY [Start] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
@Output = STUFF((SELECT ', round('+ QUOTENAME([Start])+',2) as ' + QUOTENAME([Start])
FROM #DbTemp1
GROUP BY [Start]
ORDER BY [Start] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @SQL = 'SELECT [Player],' + @Output + '
INTO #dbTemp2
FROM
(
SELECT [Player], [Start], [Average]
FROM #DbTemp1
) AS SourceTable
PIVOT
(
AVG([Average])
FOR [Start] IN (' + @Column + ')
) AS PivotTable
ORDER BY Len([Player]), Player;
select * from #DbTemp2'
EXECUTE(@SQL)