create pivot table, with dynamic columns

Posted on 2006-03-21
Last Modified: 2006-11-18

I want to create a stored procedure that takes a start month and returns a crosstab
pivot table.

My source table contains columnss:
centerNumber,YearMonth, and expenseAmount

The crosstab result should have 13 columns:
and yearMonth for 12 conscutive months.

The trick is that I want to be able to dynamically determine the start month based on the yearMonth value passed into the stored procedure. The new PIVOT TSQL statement makes this task easier, but I still don't know how to dynamically determine the month columns. Below I have a pivot table statement which always starts with Jan05, I'd like to be able to start with any month.

   Center_num,[200501] mth01,[200502] mth02, [200503] mth03,[200504] mth04,
   [200505] mth05, [200506] mth06,[200507] mth07,[200508] mth08,[200509] mth09,
   [200510] mth10,[200511] mth11,[200512] mth12
   (select Center_Num,Fund_Mth,sumExp from pri_pmpmNew_01_main ) t
   for Fund_Mth in ([200501],[200502],[200503],[200504],[200505],[200506],[200507],[200508],[200509],
) as pvt

Thanks really appreciate the help!
Question by:brokeMyLegBiking
    LVL 4

    Author Comment

    I'm using SqlServer 2005, by the way.
    LVL 15

    Expert Comment

    You could use dynamic SQL and build the select something like this.  This is just a sample of the beginning of the code to get you started.

    declare @sql varchar(1000)

    set @sql = 'select Center_num,['

    set @month = 1
    while @month <= 12
        Set @sql = @sql + @year + right('0' + cast(@month as varchar(2)),2) + '] mth' + right('0' + cast(@month as varchar(2)),2) + ','
        Set @month = @month + 1


    LVL 68

    Expert Comment

    Is the "yearMonth" an int or a (var)char?
    LVL 68

    Expert Comment

    To avoid dynamic SQL, I suggest creating 11 local variables, loading them with the values of the following 11 months, and then using code like this:

       SUM(CASE WHEN Fund_Mth = @StartMth THEN expenseAmount ELSE 0 END) AS Mth01,
       SUM(CASE WHEN Fund_Mth = @Mth02 THEN expenseAmount ELSE 0 END) AS Mth02,
       SUM(CASE WHEN Fund_Mth = @Mth12 THEN expenseAmount ELSE 0 END) AS Mth12
    from ri_pmpmNew_01_main
    where fund_mth between @StartMth and @Mth12
    group by
    LVL 4

    Author Comment

    ok Scott,  I was able to populate my 12 month varables based on the startMonth, and they I guess I can just use the case statement like you suggested.

       @startMonth8 char(8),
       @mth01 char(6),@mth02 char(6),@mth03 char(6),@mth04 char(6),@mth05 char(6),@mth06 char(6),@mth07 char(6),@mth08 char(6),@mth09 char(6),@mth10 char(6),@mth11 char(6),@mth12 char(6)
       set @startMonth8 = @startMonth + '01'
       set @mth01 = convert(char(6),dateadd(mm, 0,@startMonth8),112)
       set @mth02 = convert(char(6),dateadd(mm, 1,@startMonth8),112)
    LVL 68

    Accepted Solution

    Yep.  Since the entries in the "PIVOT" command cannot be dynamic/variable, to me that's the best method to avoid dynamic SQL -- it's good to know that at least one classic 2000 technique is still useful in 2K5 :-) .
    LVL 4

    Author Comment

    Wow, I upgraded all my servers for the PIVOT table statement, and now I'm using the classic case statement technique.. ironic.

    But there have been plenty of other benefits to upgrading to 2K5, so I don't regret it.

    thx again!

    Featured Post

    Better Security Awareness With Threat Intelligence

    See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

    Join & Write a Comment

    Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
    Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
    Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now