Dynamic Pivot SQL中的Where子句使用日期列中的日期

时间:2014-01-23 11:34:32

标签: sql datetime pivot where

我在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)

请帮忙,

谢谢, 甲

1 个答案:

答案 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