这段SQL能否从索引方面进行优化,然后写法尽量不变,因为拼接出来的。
select * from tab_A a
where (exists (select 1
from (select cst_id,
sum(decode(data_dt,'202112',fin_bal,0)) +
sum(decode(data_dt,'202112',def_bal,0)) -
sum(decode(data_dt,'202110',fin_bal,0)) -
sum(decode(data_dt,'202110',def_bal,0)) as amt
from tab_B
where data_dt in ('202112','202110')
group by cst_id) b
where b.amt > 10000
and a.cst_id = b.cst_id)
);
建议用having替代where条件,减少一层嵌套。然后建议用join替代这个exists条件。因为很明显里面的这个sql才应该是主驱动表,条件都是基于b表的,应该先确定要查哪些cst_id后,再用这些cst_id查a表。而不是针对a表的每一行去查哪些cst_id满足条件