使用AVG / Datediff / CASE的SQL查询

时间:2017-11-02 17:56:15

标签: sql sql-server case average datediff

SELECT
    AVG(
        DATEDIFF(
            day,
            P.[ProjectCreatedDate],
            CASE WHEN T.[Reported Milestones] LIKE '02 Request Assigned' THEN T.[TaskActualFinishDate]
        )
    ) AS AverageAssignmentAge

我有上述查询,我​​正在尝试查找创建日期和请求指定日期之间的平均分配日期。它不起作用,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要在case表达式中移动datediff函数,然后在聚合函数中包含整个case表达式。

CREATE TABLE Table1
    ([Reported Milestones] varchar(19), [ProjectCreatedDate] datetime, [TaskActualFinishDate] datetime)
;

INSERT INTO Table1
    ([Reported Milestones], [ProjectCreatedDate], [TaskActualFinishDate])
VALUES
    ('02 Request Assigned', '2017-10-01 00:00:00', '2017-10-10 00:00:00'),
    ('02 Request Assigned', '2017-10-01 00:00:00', '2017-10-10 00:00:00'),
    ('02 Request Assigned', '2017-10-01 00:00:00', '2017-10-10 00:00:00'),
    ('xxx', '2017-10-01 00:00:00', NULL),
    ('xxx', '2017-10-01 00:00:00', NULL)
;

注意处理任务"持续时间" "结束日期"通常是指那天的结束",但是db中记录的内容等同于那天的开始"。所以你几乎肯定想在dateiff计算中添加一个,它计算从开始日期开始到结束日期开始的天数。

SQL Fiddle

上的测试/示例
SELECT
      AVG( CASE WHEN [Reported Milestones] LIKE '02 Request Assigned' THEN 
                  DATEDIFF(DAY,[ProjectCreatedDate],[TaskActualFinishDate])+1
           END)
      AS averageassignmentage
    , COUNT( CASE WHEN [Reported Milestones] LIKE '02 Request Assigned' THEN 
                  TaskActualFinishDate
           END)
      AS sample_size
from table1

查询1

| averageassignmentage | sample_size |
|----------------------|-------------|
|                   10 |           3 |

<强> Results

{{1}}