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
相关产品推荐
相关产品推荐

