如何计算两个日期之间的天数以及多个日期的总天数

时间:2017-10-02 17:49:21

标签: sql sql-server-2000

我需要创建一个查询,计算清除日期和未清除日期之间的天数,然后计算这些日期的总和。

以下是数据集的示例:

 Name         Status         Date      Explanation
Tony Camp    Uncleared       9/4/17    Need more information.
Tony Camp    Cleared         9/7/17    Paper work signed
Tony Camp    Uncleared       9/9/17    Placement is full. 
Tony Camp    Cleared         9/25/17   Placement is ready.
Everly Mo    Uncleared       9/26/17   Not ready. 
Everly Mo    Cleared         10/01/17  Ready.
Stan Mann    Uncleared       10/01/17  Not Ready.

以下是报告的示例:

Case        Person         Number of Uncleared Days
12          Tony Camp             18
25          Everly Mo             4

我通过计算每个未清除状态和清除状态之间的天数然后添加天数来得出结果。这将为我提供每个人每个未清除和清除日期之间的总天数。

浓淡我得到了9/4/17和9/7/17之间的差异,然后是9/9/17和9/25/17之间的差异。然后我添加了几天来获得未清除天数。

1 个答案:

答案 0 :(得分:0)

你可以使用它。

;WITH CTE AS 
(
    SELECT *, 
    RN = ROW_NUMBER() OVER (PARTITION BY Name, Status ORDER BY [Date]) 
    FROM DataSet
)
SELECT 
    T1.Name Person,  
    SUM(DATEDIFF(DAY,T1.Date, T2.Date)) -1 [Number of Uncleared Days] 
FROM CTE T1 INNER JOIN CTE T2 ON T1.Name = T2.Name AND T2.Status ='Cleared' AND T1.RN = T2.RN 
WHERE T1.Status ='Uncleared'
GROUP BY T1.Name

对于SQL2000:

SELECT Person, SUM([Date_Diff]) - 1 AS [Number of Uncleared Days]  FROM
( 
    SELECT 
        D1.Name AS Person, 
        DATEDIFF(DAY, [Date] , 
            (SELECT TOP 1 [Date] 
            FROM DataSet D2 
            WHERE D2.Status ='Cleared' 
                AND D1.Name = D2.Name 
                AND D1.Date < D2.Date) ) AS [Date_Diff] 
    FROM 
        DataSet AS D1
    WHERE 
        D1.Status ='Uncleared'
) AS SubQ
WHERE 
    [Date_Diff] IS NOT NULL
GROUP BY Person