SELECT *
FROM (
SELECT [TM_UserID],
[FullName],
[Worked_dte],
[Worked_Hours]
FROM @Reporting_User_Timesheet
WHERE [worked_dte] BETWEEN '2014-04-04'
AND '2014-04-06'
) AS sourceTable
Pivot(sum([Worked_Hours]) FOR [Worked_dte] IN ([2014-04-04], [2014-04-05], [2014-04-06])) AS PivotTable
答案 0 :(得分:0)
首先,您需要一个日历表来获取范围的日期:
http://www.dbdelta.com/calendar-table-and-datetime-functions/
之后,构建所需的PIVOT查询并动态执行:
declare @range_start date, @range_end date;
select @range_start = '20140404', @range_end = '20140406';
declare @collist nvarchar(max);
SET @collist = stuff((select distinct ',' + QUOTENAME(convert(varchar,date,112))
FROM calendar
WHERE Datue BETWEEN @range_start AND @range_end
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
declare @q nvarchar(max);
set @q = '
SELECT *
FROM (
SELECT [TM_UserID],
[FullName],
[Worked_dte],
[Worked_Hours]
FROM @Reporting_User_Timesheet
WHERE [worked_dte] BETWEEN ''' + CONVERT(varchar, @range_start, 112) + '''
AND ''' + CONVERT(varchar, @range_end, 112) + '''
) AS sourceTable
Pivot (
sum([Worked_Hours]) FOR [Worked_dte] IN (' + @collist + ')
) AS PivotTable
';
exec (@q);