我需要知道两个日期范围与SQL Server共同的天数

时间:2018-08-29 11:36:41

标签: sql sql-server

我需要知道两个日期范围在mssql中共有的天数

怎么写呢?你能给我任何样品吗?

(FirstDay - SecondDay)  1. date range

(ThirdDay, FourthDay)   2.date range

SELECT 
    DAY_RANGE, 
    DATEDIFF(DAY, FirstDay, ThirdDay), 
    DATEDIFF(DAY, SecondDay, FourthDay)
FROM 
    Test 

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,我将执行以下操作:

1) Find out which of both start dates is greater
2) Find out which of both end dates is smaller
3) Calculate the number of dates between (1) and (2)

在此处查看SQL Fiddle:http://sqlfiddle.com/#!18/9eecb/32006

更新:如@CetinBasoz所述,如果没有重叠,则需要处理负的返回值。

答案 1 :(得分:0)

Murat, 您可以像这样检查重叠的日期范围:

select case 
       when FirstDay < ThirdDay then ThirdDay
       else FirstDay end as rangeStart,
       case 
       when SecondDay > FourthDay then FourthDay
       else SecondDay end as rangeEnd,
       FirstDay, SecondDay, ThirdDay, FourthDay
from myTable
where FirstDay < FourthDay and SecondDay > ThirdDay;

取决于范围的包容性,您可能更喜欢<=,> =而不是<和>。

DBFiddle demo