简体   繁体   中英

Dynamic columns using PIVOT and I need to use those dynamic columns along with aggregate function to generate reports month wise -SQL Server 2012

I'm using SQL SERVER 2012 and i am using the below query

SELECT Status AS [Status]
    ,[Feb-2016] AS [Current(Feb)]
    ,[Jan-2016]
    ,[Dec-2015]
    ,[Nov-2015]
    ,[Oct-2015]
    ,[Sep-2015]
    ,[Aug-2015]
    ,[Jul-2015]
    ,[Jun-2015]
    ,[May-2015]
    ,[Apr-2015]
    ,[Mar-2015]
    ,[Feb-2015]
INTO #TempTable
FROM (
    SELECT Status
        ,[Count]
        ,[Month]
    FROM CTE2--I'm using this Common Table Expression in the SP
    ) AS [Mnth]
PIVOT(SUM([Count]) FOR [Month] IN (
            [Feb-2016]
            ,[Jan-2016]
            ,[Dec-2015]
            ,[Nov-2015]
            ,[Oct-2015]
            ,[Sep-2015]
            ,[Aug-2015]
            ,[Jul-2015]
            ,[Jun-2015]
            ,[May-2015]
            ,[Apr-2015]
            ,[Mar-2015]
            ,[Feb-2015]
            )) AS [nNamePivot]

For the above part i can use dynamic Query


If i use dynamic query, how to get output for the below part and I need to use those dynamic columns along with aggregate function to generate reports month wise.

SELECT *
FROM #TempTable
UNION
SELECT 'Total'
    ,SUM([Current(Feb)])
    ,SUM([Jan-2016])
    ,SUM([Dec-2015])
    ,SUM([Nov-2015])
    ,SUM([Oct-2015])
    ,SUM([Sep-2015])
    ,SUM([Aug-2015])
    ,SUM([Jul-2015])
    ,SUM([Jun-2015])
    ,SUM([May-2015])
    ,SUM([Apr-2015])
    ,SUM([Mar-2015])
    ,SUM([Feb-2015])
FROM #TempTable

Please help me with this.

Another dynamic string can be created for the aggregations in the same way as you create one for column names. For example, the string for column names will look like:

[Jan-2015], [Feb-2015], [Mar-2015], [Apr-2015]  

and the string for aggregations will look like:

SUM([Jan-2015]), SUM([Feb-2015]), SUM([Mar-2015]), SUM([Apr-2015])

To create dynamic string of column names:

STUFF((SELECT ',['+col_name+']' FROM table FOR XML PATH('')),1,1,'');

and to create a string for aggregations:

STUFF((SELECT ',SUM(['+col_name+'])' FROM table FOR XML PATH('')),1,1,'');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM