I asked a similar question yesterday and the code for it is below but it does not seem to be working for this situation. I am trying to find the next visit date after a discharge but if there are multiple discharges and the next visit date is after the second or third discharge I would like the "NEXT_VISIT" to be blank. Thank you.
HAVE:
| ID_NUM | ADMIT_DATE | DISCHARGE_DATE | NEXT_VISIT |
| ------------ | ------------ | ------------ | ------------ |
| 100000301 | 4/1/2022 | 4/7/2022 | 5/18/2022 |
| 100000301 | 4/11/2022 | 4/18/2022 | 5/18/2022 |
| 100000301 | 4/18/2022 | 5/13/2022 | 5/18/2022 |
| 100000005 | 8/25/2022 | 9/1/2022 | 9/12/2022 |
| 100000005 | 10/15/2022 | 10/22/2022 | 9/12/2022 |
| 100000005 | 10/22/2022 | 11/22/2022 | 9/12/2022 |
WANT:
ID_NUM | ADMIT_DATE | DISCHARGE_DATE | NEXT_VISIT |
---|---|---|---|
100000301 | 4/1/2022 | 4/7/2022 | |
100000301 | 4/11/2022 | 4/18/2022 | |
100000301 | 4/18/2022 | 5/13/2022 | 5/18/2022 |
100000005 | 8/25/2022 | 9/1/2022 | 9/12/2022 |
100000005 | 10/15/2022 | 10/22/2022 | 10/24/2022 |
100000005 | 10/22/2022 | 11/22/2022 | 11/28/2022 |
CREATE TABLE ADMITS
(
ID_NUM INT
,ADMIT_DATE DATE NULL
,DISCHARGE_DATE DATE NULL
)
INSERT INTO ADMITS (ID_NUM, ADMIT_DATE, DISCHARGE_DATE)
VALUES
(100000301, '4/1/2022', '4/7/2022')
,(100000301, '4/11/2022', '4/18/2022')
,(100000301, '4/18/2022', '5/13/2022')
,(100000005, '8/25/2022', '9/1/2022')
,(100000005, '10/15/2022', '10/22/2022')
,(100000005, '10/22/2022', '11/22/2022');
CREATE TABLE VISITS
(
ID_NUM INT
,SERVICE_DATE DATE NULL
,PROVIDER_ID INT NULL
,SVCOD VARCHAR(10) NULL
)
INSERT INTO VISITS (ID_NUM, SERVICE_DATE, PROVIDER_ID,SVCOD)
VALUES
(100000301, '5/18/2022', 903263,'T1015')
,(100000301, '5/28/2022', 903263,'T1015')
,(100000301, '11/7/2022', 903263,'T1015')
,(100000301, '11/28/2022', 903263,'T1015')
,(100000005, '9/12/2022', 903263,'T1015')
,(100000005, '10/24/2022', 903263,'T1015')
,(100000005, '11/7/2022', 903263,'T1015')
,(100000005, '11/28/2022', 903263,'T1015');
--This worked for my previous question but not this example
SELECT A.*, (SELECT MIN(SERVICE_DATE)
FROM VISITS AS V
WHERE V.ID_NUM = A.ID_NUM
AND SERVICE_DATE > DISCHARGE_DATE) AS next_visit
FROM ADMITS AS A
2条答案
按热度按时间watbbzwu1#
This works:
See it run here:
https://dbfiddle.uk/61vjkbAu
It uses windowing functions and should perform much better than using correlated subqueries in the SELECT list.
rxztt3cl2#
This will give you what you want, but please don't use it in production code.
SQL Fiddle