我正在与一系列住院患者一起工作,如果过去12个月中在医院中出现过9次以上,则每个患者帐户都标记为“ Y”。
我想出了这一点,如果患者列表是静态的并且只包含12个月的期限,则可以很好地工作:
SELECT
ENC.HSP_ACCOUNT_ID,
ENC.PAT_MRN_ID,
ENC.ADT_ARRIVAL_DTTM,
case when count(distinct txn.hsp_account_id) over(partition by PAT.PAT_MRN_ID) >= 9 then 'Y' else 'N' end as familiar_face_yn
FROM CLARITY.F_ED_ENCOUNTERS ENC
WHERE ENC.SERVICE_DATE BETWEEN '1-JUL-17' AND '31-OCT-18'
但是我想查询前两年的数据,但只使用到达日期前的12个月(ENC.ADT_ARRIVAL_DTTM)计算Y或N。
我在上面的查询中遇到的问题是,它回溯并计算了7/1/17到10/31/18之间特定患者的所有就诊次数。
我想要的是,如果一条记录的到达日期是8/1/18,则应该将8/1/17到8/1/18之间的所有访问计数在内,而忽略任何到达日期早于8/1/17或晚于8/1/18。
这种“滚动”计算是否可能?非常感谢!
答案 0 :(得分:1)
您可以使用windowing子句:
SELECT ENC.HSP_ACCOUNT_ID, ENC.PAT_MRN_ID, ENC.ADT_ARRIVAL_DTTM,
(CASE WHEN COUNT(DISTINCT txn.hsp_account_id) OVER
(PARTITION BY PAT.PAT_MRN_ID
ORDER BY ENC.SERVICE_DATE
RANGE BETWEEN 365 PRECEDING AND CURRENT ROW
) >= 9
THEN 'Y' ELSE 'N'
END) as familiar_face_yn
FROM CLARITY.F_ED_ENCOUNTERS ENC
WHERE ENC.SERVICE_DATE BETWEEN DATE '2017-07-01' AND DATE '2018-10-31'
答案 1 :(得分:0)
with cte as
(
SELECT
ENC.HSP_ACCOUNT_ID,
ENC.PAT_MRN_ID,
ENC.ADT_ARRIVAL_DTTM,
-- find the most recent visit
max(ENC.ADT_ARRIVAL_DTTM) over(partition by PAT.PAT_MRN_ID) as last_date
FROM CLARITY.F_ED_ENCOUNTERS ENC
WHERE ENC.SERVICE_DATE BETWEEN '1-JUL-17' AND '31-OCT-18'
)
select ...
-- count all rows with within a 12 month range before the most recent visit
case when count(distinct case when ADT_ARRIVAL_DTTM >= add_months(last_date, -12) then txn.hsp_account_id end)
over (partition by PAT.PAT_MRN_ID) >= 9
then 'Y'
else 'N'
end as familiar_face_yn
from cte
我不知道您是否真的需要DISTINCT计数...