0

我正在使用 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
4

3 回答 3

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星期一。

于 2013-02-11T08:36:30.770 回答
0

Do you tried to use it?

GROUP BY DAYOFWEEK(DATEADD(D, 0, DATEDIFF(D, 0, T.TaskEndDate)))
于 2013-02-11T08:24:32.750 回答
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 与 Week

于 2013-02-11T09:01:30.447 回答