Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sql how many days one period contains in other given period

I need to calculate how many days one set period contains in another set period. I have table with

create table #test
(
,project nvarchar(10),
startProjectDate date,
endProjectDate date)

insert into #test values
('EE43213','2021-12-31','2022-01-06') ,
('EE0211213','2022-01-09','2022-03-14'), 
('EE53134','2022-02-18','2022-02-22') 

I have parameters with dates (user input in the future)

DECLARE @startDate DATE = N'2021-12-16' 
DECLARE @endDate DATE = N'2022-03-02' 

For every project I need to calculate, how many days of their running time will be set on user chosen period and then * this count on some koeff.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have case when in mind, if the whole project was in parameter-set period, I just find datediff between two project dates and * it.

case when (startProjectDate BETWEEN @startDate and @endDate) 
and (endProjectDate BETWEEN @startDate and @endDate)
 then DATEDIFF(day, startProjectDate , endProjectDate) + 1 * coeff else ...

But how to find an amount of days if they only partially set on this period?

>Solution :

Seems you just need a DATEDIFF and some CASE expressions here:

DECLARE @StartDate DATE = N'20211216',
        @EndDate DATE = N'20220302';

SELECT project,
       DATEDIFF(DAY, CASE WHEN startProjectDate < @StartDate THEN @StartDate ELSE startProjectDate END, CASE WHEN endProjectDate > @EndDate THEN @EndDate ELSE endProjectDate END) AS DaysInRange,
       DATEDIFF(DAY,startProjectDate, endProjectDate) AS DaysInProject
FROM #test
WHERE startProjectDate <= @EndDate
  AND endProjectDate >= @StartDate;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading