I\'m struggling with producing a pivot against at table of transactional data. The table of data I have is as follows:
+------------+------------+-----------+---
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