Pivot table for dynamic data

  • This is the script.

    – Create Table

    create table T1 ( [No] int, [ID] int, Date Datetime, Value decimal (38,2))

    – Insert data into the table

    insert into T1 values (1, 1001, ‘05/01/2009′, 101.00)

    insert into T1 values (1, 1001, ‘05/15/2009′, 102.00)

    insert into T1 values (1, 1001, ‘05/20/2009′, 105.00)

    insert into T1 values (2, 1001, ‘05/01/2009′, 41.00)

    insert into T1 values (2, 1001, ‘05/15/2009′, 44.00)

    insert into T1 values (3, 1001, ‘06/01/2009′, 330.00)

    – Check the Data

    select * from T1

    – Using Pivot key word to get required output

    SELECT [No] , [ID] ,[05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]

    FROM (

    SELECT [No], [ID], [Date], [Value]

    FROM T1) up

    PIVOT ( sum([Value]) FOR [Date] in ([05/01/2009] ,[05/15/2009] ,[05/20/2009] ,[06/01/2009]) )AS pvt

    Is it possible to use two aggreation in the PIVOT? If possible, can you please suggestion how to use it?

    Another thing that if i have around 100 of Dates and i want to use pivot query for this to find out the avg Value Datewise. so what to to for this ?

    e.g

  • The answers are in two excellent articles on this site by MVP Jeff Moden:

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns[/url]

    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs[/url]

    Part 1 covers your first question.

    Part 2 covers the second.

    Neat.

    edit: typo

  • Thanks for the referral, Paul.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Jeff Moden (3/8/2010)


    Thanks for the referral, Paul.

    No worries 🙂

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply