我不想动态传递working_dates,我想在pivot中的范围之间传递working_dates

时间:2014-04-04 10:00:47

标签: sql-server

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

1 个答案:

答案 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);