I'm trying to create a crosstab/pivot which takes dynamic dates and gives me the corresponding sum values for a given user at each of the respective dates.
I'm only just starting, but not sure where to go next - perhaps someone could nudge in the right direction :-)
/* create temp table */
CREATE TABLE #tmpDates
( tDate date )
INSERT into #tmpDates
VALUES
('2022-11-09'),
('2022-11-08'),
('2022-11-07')
pivot (so far)
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SELECT @cols = @cols + QUOTENAME(tDate) FROM (select distinct tDate from #tmpDates) as tmp
set @query =
N'
SELECT * from
(
SELECT
UID,
SUM(myValue) as sumValue
FROM dbo.tblTrans
WHERE myValue > 0 AND tDate <= ' + @cols + '
GROUP BY UID
) src
pivot
(
max(myValue) for cast(tDate as date) in (' + @cols + ')
) piv
'
execute(@query)
The output i'm looking for is something like
UID 2022-11-09 2022-11-08 2022-11-07
12 420 400 350
15 100 50 0