如何使用数据透视创建动态SQL

时间:2018-06-21 22:09:14

标签: sql-server sql-server-2008

我有类似这样的数据。

enter image description here

我想将其设置为如下所示。

enter image description here

我正在测试下面的SQL脚本。它不会抛出错误,但实际上也没有任何作用。

        var valFromStatic = ((NameValueCollection)ConfigurationManager.GetSection("customNameValueSectionHandlerSection"))["customKey"];
        var valFromInstance = ((AppSettingsSection)ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).GetSection("customAppSettingsSection")).Settings["customKey"].Value;

样品...

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);
    declare @startDate datetime
    declare @endDate datetime        
    set @startDate = '09/10/2017'
    set @endDate = '10/31/2017'

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.AsOfDate) 
            FROM [UNION_SUMMARY] c
            WHERE c.AsOfDate Between @startDate And @endDate
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT PID, ' + @cols + ' from 
            (
                SELECT PID,  
                Reportable_Amount,
                AsOfDate
                from [UNION_SUMMARY]
            WHERE AsOfDate Between @startDate And @endDate
           ) x
            pivot 
            (
                 SUM(Reportable_Amount)
                for AsOfDate in (' + @cols + ')
            ) p '
print @query

exec sp_executesql @query, N'@startDate date, @endDate date', @startDate = @startDate, @endDate = @endDate;

1 个答案:

答案 0 :(得分:1)

也尝试以下操作以获取“总计”行:

DECLARE @cols AS NVARCHAR(MAX),
    @query1  AS NVARCHAR(MAX),
    @query2  AS NVARCHAR(MAX);
    declare @startDate datetime
    declare @endDate datetime        
    set @startDate = '09/10/2017'
    set @endDate = '10/31/2018'

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(varchar(10), c.AsOfDate, 101)) 
            FROM dynamic_sql c
            WHERE c.AsOfDate Between @startDate And @endDate
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

DECLARE @NulltoZeroCols NVARCHAR (MAX)
SET @NulltoZeroCols = SUBSTRING((SELECT DISTINCT ',ISNULL(['+convert(varchar(10), AsOfDate, 101)+'],0) AS [AsOfDate]' 
FROM dynamic_sql GROUP BY convert(varchar(10), AsOfDate, 101) FOR XML PATH('')),2,8000)

print @NulltoZeroCols

set @query1 = 'INSERT INTO TEMP_TABLE SELECT PID, ' + @NulltoZeroCols + ' from 
            (
                SELECT PID,  
                ISNULL(cast(Reportable_Amount as numeric(5,2)), 0) Reportable_Amount,
                convert(varchar(10), AsOfDate, 101) AsOfDate
                from dynamic_sql
            WHERE AsOfDate Between @startDate And @endDate
           ) x
            pivot 
            (
                 SUM(Reportable_Amount)
                for AsOfDate in (' + @cols + ')
            ) p '
print @query1

set @query2 = 'SELECT ''Grand Total'' PID, ' + @cols + ' into temp_table from 
            (
                select  convert(varchar(10), AsOfDate, 101) AsOfDate,
                ISNULL(cast(Reportable_Amount as numeric(5,2)), 0) Reportable_Amount from dynamic_sql
            WHERE AsOfDate Between @startDate And @endDate
           ) x
            pivot 
            (
                 SUM(Reportable_Amount)
                for AsOfDate in (' + @cols + ')
            ) p '
print @query2
exec sp_executesql @query2, N'@startDate date, @endDate date', @startDate = @startDate, @endDate = @endDate;
exec sp_executesql @query1 , N'@startDate date, @endDate date', @startDate = @startDate, @endDate = @endDate;
select * from TEMP_TABLE ORDER BY LEN(PID)
drop table TEMP_TABLE