0

下面的查询带回按周分组的课程时间总和。问题是,每次无法在查询中定义周值时,它们都可能不同。以下是查询中返回的内容的示例:

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

询问

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
4

1 回答 1

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

于 2013-08-28T19:08:56.887 回答