Reputation: 9425
I have two tables defined as the following:
User (ID int, name varchar)
Hours (UserID int, [date] date, hours float)
Now i can perform a join to get the number of hours for each person like so:
SELECT U.ID, U.Name, H.[date], H.Hours
FROM Users U
LEFT JOIN Hours H ON U.ID = H.UserID
WHERE H.Date > '2011-01-01'
AND H.Date < '2011-02-01'
Which would give me a result set with the following columns (and between the date range):
ID, Name, Date, Hours
What I would like to do is change the output columns so that it appears more like a spreadsheet:
ID, Name, 2011-01-01, 2011-01-02, 2011-01-03 ..... 2011-01-31
and the corresponding columns with the correct hour values.
Is this possible?
Upvotes: 1
Views: 694
Reputation: 70668
Well, you are gonna need to use dynamic sql for that, if you want to change the date ranges. So first, take a look to this link. Then you can try the following:
DECLARE @Dates NVARCHAR(MAX), @Query NVARCHAR(MAX)
SET @Dates = ''
SELECT @Dates = @Dates + '[' + CONVERT(VARCHAR(10),[date],120) +'],'
FROM Hours
WHERE [Date] >= @StartDate AND [Date] < @EndDate
GROUP BY CONVERT(VARCHAR(10),[date],120)
ORDER BY CONVERT(VARCHAR(10),[date],120)
SET @Dates = LEFT(@Dates ,LEN(@Dates )-1)
SET @Query = '
SELECT ProviderName, '+@Dates+'
FROM ( SELECT U.ID, U.Name, H.[date], H.Hours
FROM Users U
LEFT JOIN Hours H
ON U.ID = H.UserID
WHERE H.Date >= '''+CONVERT(VARCHAR(8),@StartDate,112)+'''
AND H.Date < '''+CONVERT(VARCHAR(8),@EndDate,112)+''') T
PIVOT(SUM(Hours) FOR [date] IN ('+@Date+')) AS PT'
EXEC sp_executesql @Query
Upvotes: 2