代码之家  ›  专栏  ›  技术社区  ›  tnlewis

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

  •  -1
  • tnlewis  · 技术社区  · 7 年前

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

    以下是数据集的示例:

     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
    

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

    我得到了2017年9月4日和2017年9月7日之间的差值,然后是2017年9月9日和2017年9月25日之间的差值。然后我加上天数,得到未清理的总天数。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Serkan Arslan    7 年前

    你可以用这个。

    ;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
    

    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