Hi,
I am trying to setup the foundations of a dynamic pivot table query.
With the following
[CODE}
DECLARE @STARTDATE AS DATETIME
DECLARE @ENDDATE AS DATETIME
DECLARE @PIVOTECOLUMN AS NVARCHAR(MAX) = ''
DECLARE SQLQUERY AS VARCHAR (MAX) = ''
SET @STARTDATE = DATEADD(M, DATEDIFF(M, 0, DATEADD(MONTH, -36, GETDATE())), 0)
SET @ENDDATE = DATEADD(M, DATEDIFF(M, 0, GETDATE()), 0 )
SELECT DISTINCT @PIVOTCOLUMN += QUOTENAME(FORMAT(CF.STATEMENT_START_DATE, 'MM-yyyy')) + ','
FROM TABLE1 CF
INNER JOIN TABLE 2 CH CF.KEY1 = CH.KEY2
WHERE CH.RECEIPT_DATE BETWEEN @STARTDATE AND @ENDDATE
AND @ENDDATE BEWEEN @STARTDATE AND @ENDDATE
SET @PIVOTCOLUMN = LEFT(@PIVOTCOLUMN, LEN(@PIVOATCOLUMN) -1)
SELECT @PIVOTCOLUMN
`
[/CODE]
the main query without the += returns 36 previous months correctly in a single column.
05-2018
06-2019
07-2020
01-2020
02-2020
however with the += when I try to run select @pivotcolumn or print to see what is in @pivotcolumn
only 1 month displays like the following
01-2018
instead of
05-2018, 06-2019, 07-2020, 01-2020, 02-2020
I was wondering what I was doing wrong here and how to also get the date column output to be ascending order from oldest date to newest date
thank you