I dynamically create a pivot table based on a variable I create to account for the number of weeks.
I then used a derived table to only include weeks that actually have data in them (those weeks become my columns in the pivot table)
I Need to eliminate all the zeros in the pivot table and just leave the row blank where there is a zero.
DECLARE @cols nvarchar(MAX) = ''
DECLARE @num int = 1
WHILE @num < 53
BEGIN
IF @num IN (SELECT dt.[Week] FROM
( SELECT
DATEPART(WEEK, r.RegistrationDate) as [Week]
FROM dbo.Registration r
LEFT JOIN dbo.RegistrationType rt
ON r.RegistrationTypeID = rt.RegistrationTypeID
GROUP BY DATEPART(WEEK, r.RegistrationDate), YEAR(r.RegistrationDate), rt.RegistrationType, DATEPART(DW, r.RegistrationDate)
HAVING YEAR(RegistrationDate) = 2021 AND SUM(CASE WHEN DATEPART(WEEKDAY, r.RegistrationDate) = 1 THEN 1 ELSE 0 END) != 0
) dt
)
SELECT @cols += QUOTENAME(CAST(@num AS nvarchar)) + ','
SET @num +=1
END
SET @cols = LEFT(@cols, LEN(@cols)-1)
DECLARE @pivotQuery nvarchar(MAX)
SET @pivotQuery =
'
SELECT * FROM
(
SELECT
DATEPART(WEEK, r.RegistrationDate) as [Week],
rt.RegistrationType,
r.RegistrationID
FROM dbo.Registration r
LEFT JOIN dbo.RegistrationType rt
ON r.RegistrationTypeID = rt.RegistrationTypeID
WHERE YEAR(RegistrationDate) = 2021 AND DATEPART(WEEKDAY, r.RegistrationDate) = 1
) AS SourceTable
PIVOT
(
COUNT(RegistrationID)
FOR [Week] IN (' + @cols + ')
) as PivotTable
'
EXEC (@pivotQuery)
This is the results. I just want to leave a blank space everywhere that there is a zero