I have a table with the surgery schedule information for doctors.here is sample data i have in the table. i am trying to get the data out from the table with a extra columns like overlapflag, overlap_percenatge. here is the sample data i have in my table.
create table #Schedule_Test
(SURG_ID INT , PAT_ID VARCHAR(10),DOC_ID VARCHAR(10),PROC_BEGIN DATETIME,PROC_END DATETIME)
INSERT INTO #Schedule_Test
VALUES(1, 'PAT-01' ,'DOC-01','2015-12-09 07:00:00.000','2015-12-09 07:30:00.000')
,(2, 'PAT-02' ,'DOC-01','2015-12-09 07:15:00.000','2015-12-09 07:45:00.000')
,(3, 'PAT-03' ,'DOC-01','2015-12-09 08:00:00.000','2015-12-09 08:30:00.000')
,(4, 'PAT-04' ,'DOC-01','2015-12-09 08:15:00.000','2015-12-09 08:45:00.000')
,(5, 'PAT-05' ,'DOC-01','2015-12-09 09:00:00.000','2015-12-09 09:30:00.000')
,(6, 'PAT-06' ,'DOC-01','2015-12-09 11:00:00.000','2015-12-09 12:30:00.000')
,(7, 'PAT-07' ,'DOC-01','2015-12-09 11:30:00.000','2015-12-09 12:00:00.000')
If we look at the result set of the query, surg-01 started at 7:00 and ended at 7:30 where as surg-02 starting befor surg-01 ends which means this is overlapping procedure. And sug-03 is not over lapping with with Surg-02 but it is over lapping with the surg-04. So if any surgery overlap with other surgery in a given day then I should mark it as overlap. With my knowledge and some help form the other blogs I got this query.
**( THIS QUERY WILL EXECUTE ONLY IN 2012 OR GREATER VERSION OF SQL SERVER)**
SELECT T.*,
CASE WHEN cat.PAT_ID IS NULL THEN 'N' ELSE 'Y' END AS Overlap_Flag,
CASE WHEN cat.PAT_ID IS NULL THEN '0' ELSE CONCAT(DATEDIFF(MINUTE,T.PROC_BEGIN,cat.PROC_END)/60,'H ',DATEDIFF(MINUTE,T.PROC_BEGIN,cat.PROC_END)%60,' MIN') END AS Overlap_Time
,cat.PAT_ID as Overlapping_with_PAT_ID
FROM #SCHEDULE_TEST T
OUTER APPLY
( SELECT TOP 1 *
FROM #Schedule_Test
WHERE T.DOC_ID = DOC_ID
AND T.PROC_BEGIN > PROC_BEGIN
AND T.PROC_BEGIN < PROC_END
ORDER BY PROC_BEGIN ) cat
bust this is not exactly what i am looking for . Here is what iam looking for logic for calculating the New columns Overlap_Flg will be true(Y) if there is overlap between the procedures overlap_percentage will be calculated based on overlaptime between the procedures/total procedure time for that patient
SURG_ID PAT_ID DOC_ID PROC_BEGIN PROC_END Overlap_Flag Overlap_percentage Overlapping_with_PAT_ID
1 PAT-01 DOC-01 2015-12-09 07:00:00.000 2015-12-09 07:30:00.000 Y 50% PAT_02
2 PAT-02 DOC-01 2015-12-09 07:15:00.000 2015-12-09 07:45:00.000 Y 50% PAT-01
3 PAT-03 DOC-01 2015-12-09 08:00:00.000 2015-12-09 08:30:00.000 Y 50% PAT-04
4 PAT-04 DOC-01 2015-12-09 08:15:00.000 2015-12-09 08:45:00.000 Y 50% PAT-03
5 PAT-05 DOC-01 2015-12-09 09:00:00.000 2015-12-09 09:30:00.000 N 0% NULL
6 PAT-06 DOC-01 2015-12-09 11:00:00.000 2015-12-09 12:30:00.000 Y 50% PAT-07
7 PAT-07 DOC-01 2015-12-09 11:30:00.000 2015-12-09 12:00:00.000 Y 100% PAT-06
any HELP will be APPRECIATED