简体   繁体   中英

Select date difference between two different rows

I have a database of hospital visits and appointment visits in the same table. There are three relevant columns:

  1. PAT_KEY, which is the patient key
  2. HOSP_DISCHRG_DT, which is the date a patient was discharged from the hospital
  3. APPT_CHECKIN_DT, which is the date a patient came in for a follow-up appointment

The issue I am coming across is that even though the patient key connects the two, the HOSP_DISCHRG_DT and APPT_CHECKIN_DT are never in the same row. So, if a patient came in for a hospital visit, and then came in a week later for a follow-up appointment, they are categorized as different visits and are thus in different rows. (Thus, it's not as simple as doing a DATEDIFF)

My goal: I want to set up an indicator which is:

  • 1 if the patient was seen for an appointment within 7 days of being discharged from the hospital visit.
  • 0 if they were not seen for a follow-up appointment visit within 7 days.

Note: A patient who comes in at any time on the 7th day should be marked as a 1. For example, a patient who has a hospital visit on 2/6/2019 at 1AM who had a follow-up appt on 2/13/2019 at 3PM should be flagged as 1)

See below code for my attempt:

SELECT PAT_KEY, HOSP_DISCHRG_DT, APPT_CHECKIN_DT,

CASE 
    WHEN DATEDIFF(day, cast (APPT_CHECKIN_DT as datetime), cast (HOSP_DISCHRG_DT as datetime)) <= 7 THEN 1 
    ELSE 0 
    END AS diff

FROM dbo.visit


WHERE HOSP_ADMIT_DT != 'NA' AND HOSP_DISCHRG_DT != 'NA'
AND 
PAT_KEY IN (SELECT PAT_KEY FROM dbo.visit WHERE DICT_ENC_TYPE_KEY = 108)


ORDER BY PAT_KEY;

I expected to see a table with the patent key and when they came in for a visit, with another column 'diff' which was either a 1 or 0, and showed whether they had come in a week earlier for a visit. What I actually got was a table of zeros, unfortunately.

尝试使用子查询来获取所需的每一行并对其进行约会以获得您正在寻找的值。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM