You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中匹配条件的ANY数组内最新项查询问题

问题:获取住院患者的最新房间/床位位置信息

我已尝试解决该查询问题多日但仍未找到方案,当前查询语句如下:

SELECT e.id, case when 7768 = any(e.class) then 'INP' else 'OUT' END AS type,
    cc.display   AS typedesc,  ccc.display, 
    cccc.display AS status3 ,  pat.id       AS patid, 
    pat.gender              ,  pat.birthdate,
    l.alias      AS room_ref,  l.name       AS room_name,
    l.id         AS room_id ,  ll.id        AS bed_id,
    ll.alias     AS bed_name,  l.partof,
    concat(hn.prefix,' ',hn.given,' ',hn.family), e.plannedenddate
FROM ecosystem.encounter e
LEFT JOIN ecosystem.codeableconcept cc   ON cc.id   = any(e.class)
LEFT JOIN ecosystem.codeableconcept ccc  ON ccc.id  = e.priority
LEFT JOIN ecosystem.codeableconcept cccc ON cccc.id = e.subjectstatus
LEFT JOIN ecosystem.patient pat ON pat.id = (e.subject->>'identifier')::int
LEFT JOIN ecosystem.practitioner prac 
  ON prac.id = (SELECT (zz->'actor'->>'identifier')::int 
                FROM jsonb_array_elements(e.participant) zz 
                WHERE zz->'type'->>'code' = 'ATND')
LEFT JOIN ecosystem.humanname hn ON hn.id = any(prac.name)
LEFT JOIN (SELECT * FROM ecosystem.locations WHERE form = 7930) l 
  ON l.id = (e.location[jsonb_array_length(e.location)-1]->>'identifier')::int
LEFT JOIN (SELECT * FROM ecosystem.locations WHERE form = 7931) ll 
  ON ll.id = (e.location[jsonb_array_length(e.location)-1]->>'identifier')::int
WHERE EXISTS (
  SELECT FROM jsonb_array_elements(e.participant) AS papi
  WHERE jsonb_typeof(papi->'actor') = 'object' 
    AND (papi->'actor'->>'identifier') = '27'
    AND (papi->'actor'->>'reference') LIKE 'Organization/%')
AND e.status in ('in-progress','on-hold','discharged')
AND 3 = any(l.partof)
AND EXISTS (
  SELECT FROM jsonb_array_elements(participant) pa
  WHERE pa->'type'->>'code' = 'ATND' 
    AND pa->'actor'->>'identifier' ='99')

此前仅需获取房间信息时,以下关联逻辑有效,因为e.location的最后一个元素即为患者的房间:

left join (select * from ecosystem.locations where form = 7930) l 
on l.id = (e.location[jsonb_array_length(e.location)-1]->>'identifier')::int

但现在情况发生变化,e.location的最后一个元素可能是房间或床位,我需要筛选出匹配对应form(房间为7930,床位为7931)的最新位置项。

内容的提问来源于stack exchange,提问作者thelittlemaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:03:22