按日期的SQL透视日期中的日期未在查询中定义

时间:2013-08-28 17:57:33

标签: sql sql-server pivot

下面的查询会返回按周分组的课程小时数。问题是,每当无法在查询中定义周值时,周值可能不同。以下是查询中返回的内容示例:

ID        Category      Week of   Total Hours
1111554 Case Management 7/2/2012     7
1111554 Case Management 7/9/2012     7
1111554 Case Management 7/16/2012       7
1111554 Pre-GED         7/2/2012    3
1111554 Pre-GED         7/9/2012    3
1111554 Pre-GED         7/16/2012   3

QUERY

WITH cteSource(DOP_ID, Category, WeekOf, [Hours])
AS (
    SELECT  DOP_ID,
         Category,
        DATEADD(DAY, DATEDIFF(DAY, '19000101', [Date]) / 7 * 7 , '19000101') AS WeekOf, -- Monday
        [Hours]
    FROM    GW_PPP.dbo.SLAM_Attendence
)
SELECT      DOP_ID AS ID,
        Category,
        WeekOf AS [Week of],
        SUM([Hours]) AS [Total Hours]
FROM        cteSource
GROUP BY    DOP_ID,
        Category,
        WeekOf
ORDER BY    DOP_ID,
        Category,
        WeekOf;

同样,我无法弄清楚如何通过不在查询中定义周来来转动表格

所以在定义周的时候不要使用这样的东西:

pivot
(

 week of in ([7/2/2012], [7/9/2012],
               [7/16/2012 ])
) piv

如果可能的话,我还想逐月添加一列。这是我想要的输出:

ID            Category  7/2/2012 7/9/2012 7/16/2012 July 12 Total
1111554 Case Management     7      7         7           21 
1111554 Pre-GED             3      3         3           12

1 个答案:

答案 0 :(得分:1)

如果您不知道周值是什么,那么您必须使用动态SQL来获得结果:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DATEADD(DAY, DATEDIFF(DAY, '19000101', [Date]) / 7 * 7 , '19000101')) 
                    from GW_PPP.dbo.SLAM_Attendence
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT DOP_ID, Category, ' + @cols + ' 
            from 
            (
              SELECT  DOP_ID,
                   Category,
                  DATEADD(DAY, DATEDIFF(DAY, ''19000101'', [Date]) / 7 * 7 , ''19000101'') AS WeekOf, -- Monday
                  [Hours]
              FROM    GW_PPP.dbo.SLAM_Attendence
            ) x
            pivot 
            (
                SUM(hours)
                for weekof in (' + @cols + ')
            ) p '

execute sp_executesql @query;

请参阅SQL Fiddle with Demo