如何计算两个日期之间的天数和多个日期的总天数
How to calculate the number of days between two dates and total the number of days for multiple dates
我需要创建一个查询来计算清除日期和未清除日期之间的天数,然后计算这些天数的总和。
这里是数据集的一个例子:
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
我通过计算每个未清除和已清除状态之间的天数,然后将天数相加得出结果。这将为我提供每个人的每个未清除和清除日期之间的总天数。
Exp.我得到了 9/4/17 和 9/7/17 之间的差异,然后是 9/9/17 和 9/25/17 之间的差异。然后我加上天数以获得未清除天数的总数。
你可以用这个。
;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
我需要创建一个查询来计算清除日期和未清除日期之间的天数,然后计算这些天数的总和。
这里是数据集的一个例子:
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
我通过计算每个未清除和已清除状态之间的天数,然后将天数相加得出结果。这将为我提供每个人的每个未清除和清除日期之间的总天数。
Exp.我得到了 9/4/17 和 9/7/17 之间的差异,然后是 9/9/17 和 9/25/17 之间的差异。然后我加上天数以获得未清除天数的总数。
你可以用这个。
;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