The query below runs quickly when the "FROM" clause has only a single account number (a.account_nbr) and a single object code (a.fin_object_cd), but when I modify the query so that the FROM clause has a range of account numbers and a range of object codes, it takes a VERY long amount of time to return results. It goes from about a minute to run to 20 or more minutes.
The query does return the results I want, but I need to make it run more quickly.
What can I do? I am not sure if adding indexes to some columns would help, or if there's just a better way to write the query.
If you need more information about the tables, or what I'm trying to accomplish, please let me know.
select
a.account_nbr as "Account Number",
a.account_nm as "Account Name",
a.fin_object_cd as "Object Code",
a.fin_obj_cd_nm as "Object Code Name",
(select COALESCE(sum(fin_beg_bal_ln_amt),0) from kfsprd.gl_balance_t where account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and univ_fiscal_yr = "2015" and fin_balance_typ_cd != "CB") as "Beginning Balance",
(select COALESCE(sum(trn_ldgr_entr_amt),0) FROM kfsprd.kf_f_transaction_dtl where univ_fiscal_yr = "2015" and account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and trn_debit_crdt_cd = "D") as "Debits",
(select COALESCE(sum(trn_ldgr_entr_amt),0) FROM kfsprd.kf_f_transaction_dtl where univ_fiscal_yr = "2015" and account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and trn_debit_crdt_cd = "C" and trn_ldgr_entr_amt is not null) as "Credits",
(
(select COALESCE(sum(fin_beg_bal_ln_amt),0) from kfsprd.gl_balance_t where account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and univ_fiscal_yr = "2015" and fin_balance_typ_cd != "CB") +
(select COALESCE(sum(trn_ldgr_entr_amt),0) FROM kfsprd.kf_f_transaction_dtl where univ_fiscal_yr = "2015" and account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and trn_debit_crdt_cd = "D") -
(select COALESCE(sum(trn_ldgr_entr_amt),0) FROM kfsprd.kf_f_transaction_dtl where univ_fiscal_yr = "2015" and account_nbr = a.account_nbr and fin_object_cd = a.fin_object_cd and trn_debit_crdt_cd = "C")
) as "Ending Balance"
from kfsprd.kf_f_transaction_dtl a where univ_fiscal_yr = "2015" and (univ_fiscal_prd_cd between "01" and "13" or
univ_fiscal_prd_cd = "BB") and a.account_nbr between "1014000" and "1014005" and a.fin_object_cd between "0000" and "9999" and a.fin_balance_typ_cd != "CB"
group by account_nbr, fin_object_cd
order by account_nbr, fin_object_cd;