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