/*
INSERT INTO TC79(PatientID,AdmissionDate,DischargeDate,Cost)
SELECT * FROM (
SELECT 709,TO_DATE('2011-07-27','YYYY-MM-DD'),TO_DATE('2011-07-31','YYYY-MM-DD'),450 FROM DUAL
UNION ALL
SELECT 709,TO_DATE('2011-08-01','YYYY-MM-DD'),TO_DATE('2011-08-23','YYYY-MM-DD'),2070 FROM DUAL UNION ALL
SELECT 709,TO_DATE('2011-08-31','YYYY-MM-DD'),TO_DATE('2011-08-31','YYYY-MM-DD'),90 FROM DUAL UNION ALL
SELECT 709,TO_DATE('2011-09-01','YYYY-MM-DD'),TO_DATE('2011-09-14','YYYY-MM-DD'),1260 FROM DUAL UNION ALL
SELECT 709,TO_DATE('2011-12-01','YYYY-MM-DD'),TO_DATE('2011-12-31','YYYY-MM-DD'),2790 FROM DUAL UNION ALL
SELECT 1624,TO_DATE('2011-06-07','YYYY-MM-DD'),TO_DATE('2011-06-28','YYYY-MM-DD'),1980 FROM DUAL UNION ALL
SELECT 1624,TO_DATE('2011-06-29','YYYY-MM-DD'),TO_DATE('2011-07-31','YYYY-MM-DD'),2970 FROM DUAL UNION ALL
SELECT 1624,TO_DATE('2011-08-01','YYYY-MM-DD'),TO_DATE('2011-08-02','YYYY-MM-DD'),180 FROM DUAL
)
*/
WITH CTE AS(
SELECT T.*, LEAD(ADMISSIONDATE,1) OVER(PARTITION BY PATIENTID ORDER BY ADMISSIONDATE) AS NEXTADMISSIONDATE,
CASE WHEN LEAD(ADMISSIONDATE,1) OVER(PARTITION BY PATIENTID ORDER BY ADMISSIONDATE)=T.DISCHARGEDATE+1 THEN 1
ELSE 0 END AS ISCONT
FROM TC79 T)
SELECT A.*
, CASE WHEN A.ISCONT =1 THEN
( SELECT MIN(DISCHARGEDATE) FROM CTE B WHERE B.ADMISSIONDATE>A.ADMISSIONDATE AND A.ISCONT<>B.ISCONT AND A.PATIENTID=B.PATIENTID)
ELSE A.DISCHARGEDATE END AS DISCHARGEDATE
FROM CTE A