按周分组日期和记录

时间:2013-02-11 08:17:46

标签: sql sql-server-2008

我正在使用sql server 2008:

我有一个查询,计算每天的任务总数和已完成任务总数

我需要每周使用相同的逻辑(几天内)。 我没有必要每天都有记录(这有关系吗?,如果是这样的话,我怎样才能插入空日记录?)。

以下是每天计算任务的当前查询:

SELECT
    DATEADD(D, 0, DATEDIFF(D, 0, T.TaskEndDate)) AS 'EndDate',
    COUNT(T.TaskID)NumOfTasks,
    COUNT(CASE WHEN T.TaskRecordsStatus = 2 THEN T.TaskID END) NumOfCompleteTasks
FROM 
    dwh.Bks_DWH_TaskRecords_V1 T
GROUP BY
    DATEADD(D, 0, DATEDIFF(D, 0, T.TaskEndDate))
ORDER BY 
    DATEADD(D, 0, DATEDIFF(D, 0, T.TaskEndDate)) DESC

这是查询输出(几行作为样本):

End Date NumOfTasks NumOfCompleteTasks
2015-06-27 00:00:00.000 1   0
2013-09-17 00:00:00.000 1   0
2013-02-11 00:00:00.000 1   1
2013-02-07 00:00:00.000 4   0
2013-02-06 00:00:00.000 1   0
2013-02-04 00:00:00.000 1   0
2013-01-20 00:00:00.000 2   0
2013-01-19 00:00:00.000 1   0
2013-01-18 00:00:00.000 2   0
2013-01-17 00:00:00.000 5   0

这是必需的结果:

End Date NumOfTasks NumOfCompleteTasks
2013-01-01 00:00:00.000 10  0
2013-01-07 00:00:00.000 6   1
2013-01-14 00:00:00.000 0   0
2013-01-21 00:00:00.000 0   0
2013-01-28 00:00:00.000 7   3
2013-02-05 00:00:00.000 2   1
2013-02-12 00:00:00.000 0   0

3 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT EndDate = Dateadd(week, Datediff(week, 0, T.TaskEndDate), 0), 
       NumOfTasks = COUNT(T.TaskID),
       NumOfCompleteTasks = COUNT(CASE WHEN T.TaskRecordsStatus = 2 THEN T.TaskID END)
FROM 
   dwh.Bks_DWH_TaskRecords_V1 T
GROUP BY
    Dateadd(week, Datediff(week, 0, T.TaskEndDate), 0)
ORDER BY 
    Dateadd(week, Datediff(week, 0, T.TaskEndDate), 0) DESC
带有简化数据的

SQL-Fiddle

这假设您希望星期一作为一周的第一天,因为日期0是1900-01-01星期一。

答案 1 :(得分:0)

你试过用吗?

GROUP BY DAYOFWEEK(DATEADD(D, 0, DATEDIFF(D, 0, T.TaskEndDate)))

答案 2 :(得分:0)

尝试

SELECT
    DATEADD(D, DATEDIFF(D, T.TaskEndDate, 0), 0) AS 'EndDate',
    COUNT(T.TaskID) NumOfTasks,
    SUM(CASE WHEN T.TaskRecordsStatus = 2 THEN 1 ELSE 0 END) NumOfCompleteTasks
FROM 
    dwh.Bks_DWH_TaskRecords_V1 T
GROUP BY
    DATEADD(D, DATEDIFF(D, T.TaskEndDate, 0), 0)
ORDER BY 
    DATEADD(D, DATEDIFF(D, T.TaskEndDate, 0), 0) DESC

对于每周版本更改D,每个DATEADD使用周