I have a temp table that has an entityID, a start date, an end date, and number of days. I get the number of days by getting the datediff between start and end dates and +1 day. The problem that I am having is when an entity has a second record that has the same start date as its previous end date, I get the number of days as 1 too many. ie.:
EntityID StartDate EndDate NumOfDays
-------- --------- ------- ---------
3414 02/01/2018 02/02/2018 2
3414 02/02/2018 02/10/2018 9
I need to make the StartDate of the second record to be 02/03/2018 and NumOfDays becomes 8 so that the whole range of days is 10 which would be correct. The temp table is ordered on EntityID, StartDate. There would be thousands of records in the table and maybe a few hundred that has this case. I only need to change the start date if that entity's previous end date is the same.
Should I do a loop? Cursor? Or is there a better way?
We are on SQL Server 2014
First, it seems that you should be calculating the number of days without the end date. That would solve the problem. But, that might not work.
You can use an updatable CTE:
with toupdate as (
select t.*, lag(end_date) over (partition by entityid order by start_date) as prev_end_date
from t
)
update toupdate
set numofdays = numofdays - 1
where prev_end_date = end_date;
Declare @t TABLE (EntityID INT, StartDate DATE, EndDate DATE)
INSERT INTO @t VALUES
(3414 ,'02/01/2018','02/02/2018'),
(3414 ,'02/02/2018','02/10/2018');
WITH x AS (
SELECT t.*
, CASE WHEN LAG(EndDate) OVER (PARTITION BY EntityID ORDER BY StartDate) >= StartDate
THEN DATEADD( DAY , 1 , LAG(EndDate) OVER (PARTITION BY EntityID ORDER BY StartDate))
ELSE StartDate END NewStartDate
FROM @t t
)
SELECT EntityID
, NewStartDate
, EndDate
, DATEDIFF(DAY, NewStartDate , EndDate) + 1 AS NumOfDays
FROM X
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.