Pivot with multiple columns

前端 未结 1 615
南笙
南笙 2021-01-28 06:18

I\'m struggling with producing a pivot against at table of transactional data. The table of data I have is as follows:

+------------+------------+-----------+---         


        
相关标签:
1条回答
  • 2021-01-28 06:56

    Your pivot statements were using For Customer instead of the actual column you were trying to pivot.

    You should also use the Count() Over() window function instead of 1 as TransCount to get the correct counts.

    This can be done dynamically by replacing the sums in the select statement and the column names in the pivot statements pretty easily.

    SELECT
        [Date],
        Customer,
        SUM(StoreA) StoreA,
        SUM(StoreB) StoreB,
        SUM(StoreC) StoreC,
        SUM(StoreAct) StoreAct,
        SUM(StoreBct) StoreBct,
        SUM(StoreCct) StoreCct
    FROM
        (SELECT
            Date,
            Customer,
            Value,
            Store,
            COUNT(*) OVER (PARTITION BY date,customer,store) AS TransCount,
            Store + 'ct' AS storecount
         FROM
            SourceTable
        ) AS s 
    PIVOT
    ( SUM(Value) FOR [Store] IN ([StoreA],[StoreB],[StoreC]) ) AS pvt 
    PIVOT
    ( SUM(Transcount) FOR storecount IN ([StoreAct],[StoreBct],[StoreCct]) ) AS pvt
    GROUP BY
        [Date],
        Customer
    
    0 讨论(0)
提交回复
热议问题