I am trying to get an SQL Server Dynamic Pivot table to work that allows me to count and then sum the number of columns. The purpose of the pivot table is to create a report of all the days individuals were staying in a city and the total number of days(in a month). So, for example, Person A was staying everyday in June - the total will be 30.Person B only started staying on the 3rd of June - the total will be 27 etc. The data table only consists of Name, ArriveDate, DepartDate...the days of the month are created through an SQL query.
+------+------------+------------+-------+-------+-------+-----+-------+-------+-------+
| Name | ArriveDate | DepartDate | 06-01 | 06-02 | 06-03 | ... | 06-29 | 06-30 | Total |
+------+------------+------------+-------+-------+-------+-----+-------+-------+-------+
| A | 2014-06-01 | 2014-06-23 | 1 | 1 | 1 | ... | 1 | 1 | 30 |
| B | 2014-06-02 | 2014-06-23 | 0 | 1 | 1 | ... | 1 | 1 | 27 |
| C | 2014-06-02 | 2014-06-23 | 0 | 0 | 0 | ... | 1 | 1 | 16 |
+------+------------+------------+-------+-------+-------+-----+-------+-------+-------+
Here is the query I have so far:
DROP TABLE #tempDates
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
;WITH cte (datelist, maxdate) AS
(
SELECT MIN(ArriveDate) datelist,
EOMONTH(GETDATE()) AS maxdate
FROM Reservation
UNION ALL
SELECT dateadd(dd, 1, datelist), maxdate
FROM cte
WHERE datelist < maxdate
)
SELECT c.datelist
INTO #tempDates
FROM cte c
SELECT @cols = STUFF(( SELECT distinct ',' + QUOTENAME(convert(CHAR(10), datelist, 120))
FROM #tempDates
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT ID,
ArriveDate,
DepartDate,
' + @cols + '
FROM
(
SELECT r.ID,
r.ArriveDate,
r.DepartDate,
d.datelist,
convert(CHAR(10), datelist, 120) PivotDate
FROM
Reservation r
LEFT JOIN
#tempDates d
ON d.datelist BETWEEN rg.ArriveDate AND GETDATE()
) x
pivot
(
COUNT(datelist)
FOR PivotDate IN (' + @cols + ')
) p '
EXECUTE (@query)