You would do it differently:
SELECT [Date], [Name], COUNT(*) FROM ... GROUP BY [Date], [Name];
Then maybe you could collapse, but you don't have to do this in the request. If you donβt know the names that you have (and therefore the number of columns), you will need dynamic SQL to create the correct vertex - but again, you can transfer this information at the presentation level and let SQL Server return this data in the way It is optimized to do.
However, I am sure that bluefeet will appear soon to give an example.
Actually, the blue foot is gone, so I will write:
DECLARE @date DATE = '2013-07-01'; DECLARE @sql NVARCHAR(MAX) = N'', @cols NVARCHAR(MAX) = N''; SELECT @cols += STUFF((SELECT ',' + QUOTENAME(Name) FROM dbo.LoginData WHERE [Date] >= @date GROUP BY Name FOR XML PATH('')), 1, 1, ''); SET @sql = N'SELECT * FROM (SELECT * FROM dbo.LoginData AS d WHERE [Date] >= @date ) AS d PIVOT (COUNT([Name]) FOR [Name] IN (' + @cols + ')) AS p;'; EXEC sp_executesql @sql, N'@date DATE', @date;
SQLfiddle demo
source share