我有两个查询,我想在不创建函数的情况下加入它们。第一个给了我当前余额的结果。结果是 160€:
select sum(SESSIONS.PRICE) - sum(SESSIONS.AMOUNT) as v_diff
from SESSIONS
where SESSIONS.CLIENTS_ID =:P2002_ID
and SESSIONS.STATUS in (4,5);
第二个查询给出了额外的付款。结果是 30 欧元:
select sum(SESSIONS.AMOUNT) as v_extra_amount
from SESSIONS
where SESSIONS.CLIENTS_ID = :P2002_ID
and SESSIONS.STATUS = 1
and SESSIONS.PAYMENT_STATUS = 2;
所以我想如果有可能通过一个查询给我 130 欧元的金额! (第一个 160 欧元 - 第二个 30 欧元)。
答案 0 :(得分:3)
只需使用条件聚合:
select (sum(case when s.STATUS in (4, 5) then s.PRICE else 0 end) -
sum(case when s.STATUS in (4, 5) then s.AMOUNT else 0 end)
),
sum(case when s.STATUS = 2 then s.AMOUNT end)
into v_diff, v_extra_amount
from SESSIONS s
where s.CLIENTS_ID = :P2002_ID;
或者,如果您想要一个值,只需减去:
select (sum(case when s.STATUS in (4, 5) then s.PRICE else 0 end) -
sum(case when s.STATUS in (4, 5) then s.AMOUNT else 0 end) -
sum(case when s.STATUS = 1 and s.PAYMENT_STATUS = 2 then s.AMOUNT end)
)
from SESSIONS s
where s.CLIENTS_ID = :P2002_ID;