我有这个查询:
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,'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,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,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,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;