我在sql pivot中使用WHERE子句,它可以工作:
SELECT Customer AS [Currency Per Customer], [USD], [EUR], [RUR], [CHF], [GBP]
FROM
(SELECT Customer, Amount, Currency
FROM Alpha.dbo.Beta
WHERE Date between '2010-01-01' and '2013-12-31'
)
x PIVOT
(
SUM(Amount)
FOR Currency IN ([USD], [EUR], [RUR], [CHF], [GBP])
) AS PivotTable
ORDER BY Customer;
但是,当我尝试在动态数据透视表中执行此操作时,它表示2010附近的语法不正确。我应该在哪里放置此WHERE子句..?如果我在这里它没有正常工作。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(currency)
FROM Alpha.dbo.Beta
WHERE Date Between '2012-01-01' and '2013-12-31'
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query = 'SELECT Customer, ' + @cols + ' FROM
(
SELECT Customer, Amount, Currency
FROM Alpha.dbo.Beta
) x
PIVOT
(
SUM(Amount)
for Currency in (' + @cols + ')
) AS pvt
ORDER BY Customer; '
execute(@query)
请帮忙,
谢谢, 甲
答案 0 :(得分:0)
试试这个:
SET @query = 'SELECT Customer, ' + @cols + ' FROM
(
SELECT Customer, Amount, Currency
FROM Alpha.dbo.Beta
WHERE Date between ''2010-01-01'' and ''2013-12-31''
) x
PIVOT
(
SUM(Amount)
for Currency in (' + @cols + ')
) AS pvt
ORDER BY Customer; '
或者,使用sp_executesql
并使用参数。像这样:
exec sp_executesql @sql, N'@start date, @end date', @start = '2010-01-01', @end = '2013-12-31'
然后where
看起来像:
WHERE Date between @start and @end