简体   繁体   English

选择两个不同行之间的日期差异

[英]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 PAT_KEY,这是患者的关键
  2. HOSP_DISCHRG_DT, which is the date a patient was discharged from the hospital HOSP_DISCHRG_DT,即病人出院的日期
  3. APPT_CHECKIN_DT, which is the date a patient came in for a follow-up appointment APPT_CHECKIN_DT,即病人进行后续预约的日期

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. 我遇到的问题是,即使患者密钥连接两者,HOSP_DISCHRG_DT和APPT_CHECKIN_DT也不会在同一行。 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) (因此,它并不像做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. 1如果患者在出院后7天内被预约接受预约。
  • 0 if they were not seen for a follow-up appointment visit within 7 days. 0如果他们在7天内没有被视为后续预约访问。

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) 注意:第7天任何时间进入的患者都应标记为1.例如,在2/6/2019凌晨1点就医院就诊并且在2/13进行了随访的患者/ 2019年下午3点应标记为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. 我希望看到一张带有专利密钥的表,当他们进来访问时,另一列'差异'是1或0,并显示他们是否在一周前来访问。 What I actually got was a table of zeros, unfortunately. 不幸的是,我实际得到的是一张零表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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