Pivots with dynamic columns in SQL Server

后端 未结 2 997
-上瘾入骨i
-上瘾入骨i 2020-12-01 23:56

I am working on an SQL Query using pvots with dynamic columns in SQL Server (T-sql). Rather than submitting my lengthy query, I’m illustrating my problem with a simplified

2条回答
  •  失恋的感觉
    2020-12-02 00:48

    Adding another answer, since this the edit almost a second question. (Without details and specifics, I can only offer general outlines and psuedo code—I don’t know SAP.)

    Let’s start with the pivot. It needs to generate columns labeled by, presumably, month, which you had in your example as Table1.Col_Name, a varchar(10); those values are extracted and dynamically added to the pivot query as column names. If there is no such column in the database, then you have to construct it for the query based on the data the user enters. I’ll work with the following assumptions: - The data has a dateime column, where any value (year through millisecond) may be found - The user specifies a “start date” (is it always the first of a month?) and you have to generate columns for that and the following 11 months, aggregating the data that falls within each target month.

    Step 1, I’d set up and populate a temp table containing the 12 target columns:

    CREATE TABLE #Months
     (
       Col_Name    varchar(10)
      ,MonthStart  datetime
      ,MonthEnd    datetime
    )
    

    Label is formatted as you want it to appear, MonthStart would be the absolute start of the month (say, Oct 1, 2011 00:00:00.000), and MonthEnd would be the absolute start of the next month (Nov 1, 2011 00:00:00.000) – this allows you to use SELECT … from

    where DataDate >= MontStart and DataDate < MonthEnd to get all data within that month.

    Next, join this table on your data table and aggregate, something like:

    SELECT
       mt.Col_Name
      ,sum(dt.RawData)  Amount
     from #Months mt
      inner join MyData dt
       on dt.DataDate >= mt.MonthStart
        and dt.DataDate < mt.MonthEnd  --  Yes, ON clauses don't have to be simple equivalencies!
      inner join 
    

    Plug this in as the innermost query of the pivot statement, extract/build the list of Col_Names from the temp table using the non-XML query (I don't know what else to call it), build and execute dynamically, and you should be good.

    提交回复
    热议问题