Creating rows from Columns ....

  • I need to create an SP where I am being passed a SQL query and need to convert the data so that some of the columns remain as columns and some of the columns become rows in the returned record set.

    The passed SQL will look something like: SELECT  A1.Geography_ID, AL1.Region_Nm, AL1.State_Nm, AL3.Data_Yr,  AL2.SalesRate, AL2.TotSales, AL2.Items FROM TIME_PERIOD_DIM AL3, GEOGRAPHY_DIM AL1 LEFT OUTER JOIN SALES_FACT AL2 ON (AL1.Geography_ID=AL2.Geography_ID) WHERE (AL3.Time_Period_ID=AL2.Time_Period_ID)  AND (AL3.Time_Period='2002' AND AL1.Geography_Typ=1)

    What I need is the resulting table to have Geography_ID, Region_Nm, State_Nm, and Data_Yr, and new colums Column_ Name and Value.

    If the query returns:

    Geography_IDRegion_NmState_NmData_YrSalesRateTotSalesItems
    1EastVA20025.9453
    2WestWA20027.1332

    I would like:

    Geography_IDRegion_NmState_NmData_YrColumn_NameValue
    1EastVA2002SalesRate5.9
    1EastVA2002TotSales45
    1EastVA2002Items3
    2WestWA2002SalesRate7.1
    2WestWA2002TotSales33
    2WestWA2002Items2

    Now I will be getting queries with unknown columns, I will be given the names of the colums to keep (the green above) but they may not always be the first columns.

     

    Thanks

  • I'm not sure how to solve the dynamic nature of what your discussing, but a query to return as your example requests

    SELECT  A1.Geography_ID, AL1.Region_Nm, AL1.State_Nm, AL3.Data_Yr,  AL2.SalesRate

    FROM TIME_PERIOD_DIM AL3, GEOGRAPHY_DIM AL1

    LEFT OUTER JOIN SALES_FACT AL2 ON (AL1.Geography_ID=AL2.Geography_ID)

    WHERE (AL3.Time_Period_ID=AL2.Time_Period_ID) 

    AND (AL3.Time_Period='2002' AND AL1.Geography_Typ=1)

    union

    SELECT  A1.Geography_ID, AL1.Region_Nm, AL1.State_Nm, AL3.Data_Yr,  AL2.TotSales,

    FROM TIME_PERIOD_DIM AL3, GEOGRAPHY_DIM AL1

    LEFT OUTER JOIN SALES_FACT AL2 ON (AL1.Geography_ID=AL2.Geography_ID)

    WHERE (AL3.Time_Period_ID=AL2.Time_Period_ID) 

    AND (AL3.Time_Period='2002' AND AL1.Geography_Typ=1)

    Union

    SELECT  A1.Geography_ID, AL1.Region_Nm, AL1.State_Nm, AL3.Data_Yr,  AL2.Items

    FROM TIME_PERIOD_DIM AL3, GEOGRAPHY_DIM AL1

    LEFT OUTER JOIN SALES_FACT AL2 ON (AL1.Geography_ID=AL2.Geography_ID)

    WHERE (AL3.Time_Period_ID=AL2.Time_Period_ID) 

    AND (AL3.Time_Period='2002' AND AL1.Geography_Typ=1)

    Maybe you can go from there

     

  • Ray - Thanks, I am doing that now but the problem is that we will need this capability in our next data release.

    Thanks

  • for something that dynamic I'll create the query client side. Ah and change the "union" for "union all"

     


    * Noel

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

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