You need to enable JavaScript to run this app. Oracle SQL合并两个同患者ID的查询获取合并结果集
优惠活动
大模型
产品
解决方案
定价
更多

Oracle SQL合并两个同患者ID的查询获取合并结果集

我有如下查询:

with rws as (
    select c.ID as P_ID, c.FIRST_NAME || ' ' || c.LAST_NAME as PATIENT, to_char(s.SESSION_DATE, 'MON-YYYY') as SESSION_MONTH,
    to_char(s.SESSION_DATE, 'DD-MM-YYYY') as SESSION_DATE,
        row_number () over (
            partition by CLIENTS_ID
            order by c.ID asc
        ) rn
    from   SESSIONS s inner join CLIENTS c
    on c.ID = s.CLIENTS_ID
    where c.ACTIVE = 2
)
  select * from rws
  where  rn <= 1
  order  by P_ID asc;

该查询返回结果如下:
首次查询返回结果

另外我还有如下查询:

select c.ID as P_ID, c.FIRST_NAME || ' ' || c.LAST_NAME as PATIENT, count(s.Id) as Qty, sum(s.AMOUNT) as PAID,
sum(s.PRICE-s.AMOUNT) as Dif
from SESSIONS s inner join CLIENTS c
on c.ID = s.CLIENTS_ID
where c.ACTIVE =2
and s.STATUS = 5
group by c.ID, c.FIRST_NAME || ' ' || c.LAST_NAME
order by P_ID;

该查询返回结果如下:
第二次查询返回结果

两个查询的患者ID字段一致,请问是否可以将两个查询合并为一个,得到如下结果?
期望的合并查询结果


正确合并查询代码

感谢 @Sam Ware 提供的实现代码如下:

with rws as (
    select p.ID as P_ID, p.FIRST_NAME || ' ' || p.LAST_NAME as PATIENT, to_char(s.SESSION_DATE, 'MON-YYYY') as SESSION_MONTH,
    to_char(s.SESSION_DATE, 'DD-MM-YYYY') as SESSION_DATE,
        row_number () over (
            partition by CLIENTS_ID
            order by p.ID asc
        ) rn
    from   SESSIONS s inner join CLIENTS p
    on p.ID = s.CLIENTS_ID
    where p.ACTIVE = 2
), transactions as (
    select p.ID as P_ID, count(s.Id) as Qty, sum(s.AMOUNT) as PAID,
        sum(s.PRICE-s.AMOUNT) as Dif
    from SESSIONS s inner join CLIENTS p
        on p.ID = s.CLIENTS_ID
    where p.ACTIVE =2
        and s.STATUS = 5
    group by p.ID
    order by P_ID
)
  select r.*, t.Qty, t.PAID, t.Dif
  from rws r
  inner join transactions t
    on r.p_id = t.p_id
  where r.rn <= 1
  order by r.P_ID asc;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:30:05