我有2个查询需要合并为1个查询,它们从同一张表中获取数据,但它们之间的差异很小
我需要合并以下查询:
select sum(balance_delta) as "Not Rental"
from h_driver_balance
where
changed between (select current_date - interval '1 days') and (select current_date)
and driver_balance_id in (select id
from driver
where driver_ds_account_id = 16
and callsign not like '0%')
and comment like 'Refill on the terminal 1%';
和
select sum(balance_delta) as "Rental"
from h_driver_balance
where
changed between (select current_date - interval '1 days') and (select current_date)
and driver_balance_id in (select id
from driver
where driver_ds_account_id = 16
and callsign like '0%')
and comment like 'Refill on the terminal 1%';
我曾经尝试过使用WITH和UNION,但是我似乎不了解某些东西。
答案 0 :(得分:1)
如果需要两列,则可以通过单个查询和条件聚合来完成:
select sum(b.balance_delta) filter (where d.callsign not like '0%') as "Not Rental",
sum(b.balance_delta) filter (where d.callsign like '0%') as "Rental"
from h_driver_balance b
join driver d on d.id = b.driver_balance_id
where b.changed between current_date - interval '1 days' and current_date
and d.driver_ds_account_id = 16
and b.comment like 'Refill on the terminal 1%';