我想将以下数据转换为SQL中的pivot。 (显示相应列“周”的“总”值和相应的行“名称”)并且在运行sp时,它会抛出异常:
将数据类型nvarchar转换为datetime时出错。
并且
PIVOT运算符中提供了错误的值“@ Week1”。
我的疑问是:
[Name] [nvarchar](255) NULL,
[Weeks] [DATETIME] NULL,
[total] [float] NULL
@Week1 = '12/6/2015'
@Week2 = '12/13/2015'
@Week3 = '12/20/2015'
@Week4 = '12/27/2015'
SELECT Name, @Week1 AS Week1, @Week2 AS Week2, @Week3 AS Week3, @Week4 AS Week4
INTO #TempData
FROM
(
SELECT Name, Weeks, total FROM #TempData2
) Data
PIVOT
(
SUM([total])
FOR [Weeks] IN ([@Week1],[@Week2],[@Week3],[@Week4])
) Piv
我为所有列提供了datetime
的数据类型,但它会导致nvarchar
到datetime
错误。我试过一些解决方案,但它没有用。
感谢您的帮助......
答案 0 :(得分:1)
在PIVOT查询中使用变量作为列占位符并不起作用。使用以下SQL查询后,我可以生成大部分结果:
SELECT
Name,
[2015-12-06 00:00:00] AS '12/6/2015',
[2015-12-13 00:00:00] AS '12/13/2015',
[2015-12-20 00:00:00] AS '12/20/2015',
[2015-12-27 00:00:00] AS '12/27/2015'
FROM
(
SELECT Name, Weeks, total
FROM #TempData
) Data
PIVOT
(
SUM([total])
FOR [Weeks] IN ([2015-12-06 00:00:00], [2015-12-13 00:00:00], [2015-12-20 00:00:00],[2015-12-27 00:00:00])
) Piv
生成如下所示的输出,但是您将看到“总计”列不存在。
要添加Grand Total
列,您需要创建一个派生表,该表对总计求和,然后加入它。类似的东西:
SELECT T1.*, T2.GrandTotal
FROM
(
SELECT
Name,
[2015-12-06 00:00:00] AS '12/6/2015',
[2015-12-13 00:00:00] AS '12/13/2015',
[2015-12-20 00:00:00] AS '12/20/2015',
[2015-12-27 00:00:00] AS '12/27/2015'
FROM
(
SELECT Name, Weeks, total FROM #TempData
) Data
PIVOT
(
SUM([total])
FOR [Weeks] IN
(
[2015-12-06 00:00:00], [2015-12-13 00:00:00],
[2015-12-20 00:00:00], [2015-12-27 00:00:00]
)
) Piv
) T1
JOIN
(
SELECT Name, SUM(Total) AS GrandTotal
FROM #TempData
WHERE Weeks IN
(
'2015-12-06 00:00:00',
'2015-12-13 00:00:00',
'2015-12-20 00:00:00',
'2015-12-27 00:00:00'
)
GROUP BY Name
) AS T2 ON T2.Name = T1.Name
结果:
您可以对SQL进行概括,以便您不必多次输入日期。在下面的SQL命令中,我假设您希望在示例数据中存在相邻的周数:
DECLARE @StartDate datetime = '2015-12-06 00:00:00';
DECLARE @StartWeek int;
SELECT @StartWeek = DATEPART(WEEK, @StartDate);
SELECT Name, [0], [1], [2], [3]
FROM
(
SELECT
Name,
DATEPART(WEEK, Weeks) - @StartWeek AS WeekNumber,
Total
FROM #TempData
WHERE DATEPART(WEEK, Weeks) BETWEEN @StartWeek AND (@StartWeek + 3)
) Data
PIVOT
(
SUM([total])
FOR [WeekNumber] IN ([0], [1], [2], [3])
) Piv
这会产生以下结果。虽然您已将列标题丢失为日期,但您可以通过更改单个变量来更改日期。