如何使用DATEDIFF计算剩余天数

时间:2018-07-01 03:04:01

标签: sql datediff getdate sql-server-2017

我写了一个基本查询来显示所有项目,到期日和完成状态,但是我想扩展查询以显示完成的天数,应该显示每个未完成项目的剩余天数。如何使用DATEDIFF函数来达到预期的效果?

我可以使用

=IIF(DATEDIFF(duedate.Day, Fields!Created.Value, Today) < 30, 1, 0)

输出:

id  name    duedate     today   
---------------------------------------------------------------
1   Alpha   2040-01-01  2018-07-01T01:49:43.943Z    Incomplete
2   Bravo   2030-03-01  2018-07-01T01:49:43.943Z    Incomplete
3   Charlie 2017-02-01  2018-07-01T01:49:43.943Z    Complete
4   Delta   2017-04-01  2018-07-01T01:49:43.943Z    Complete

我当前的查询:

SELECT 
    id, name, duedate, GETDATE() AS today,
    CASE 
       WHEN duedate <= CURRENT_TIMESTAMP THEN 'Complete'
       WHEN duedate >= CURRENT_TIMESTAMP THEN 'Incomplete'
    END
FROM 
    Project
ORDER BY 
    Project.name ASC;

所需结果:

id  name    duedate     today                       Status      daystocomp
--------------------------------------------------------------------------
1   Alpha   2040-01-01  2018-07-01T01:49:43.943Z    Incomplete  8030 or 22y1m1d
2   Bravo   2030-03-01  2018-07-01T01:49:43.943Z    Incomplete  4380 or 12y1m1d
3   Charlie 2017-02-01  2018-07-01T01:49:43.943Z    Complete    0
4   Delta   2017-04-01  2018-07-01T01:49:43.943Z    Complete    0

1 个答案:

答案 0 :(得分:1)

是的,您可以使用datediff()

SELECT id, name, duedate, GETDATE() AS today,
       (CASE WHEN duedate <= CURRENT_TIMESTAMP THEN 'Complete'
             WHEN duedate > CURRENT_TIMESTAMP THEN 'Incomplete'
        END),
       (CASE WHEN duedate > CURRENT_TIMESTAMP
             THEN DATEDIFF(day, CURRENT_TIMESTAMP, duedate)
        END) as daystocomp
FROM Project
ORDER BY Project.name asc;