可能であれば、ネストされた選択されたステートメントの使用を避けたいと思います (パフォーマンスの問題が発生すると思われます)。金融取引テーブルから取引の種類ごとに合計を取得しようとしています。同じテーブルから複数の選択を使用できると思いますが、「BFWD」の数字は"bil_yer + 1"
( raw だけでなくbil_yer
)結果を返します。どんな提案でも大歓迎です。
SELECT bil_yer,
acc_num,
ubsgch_key_num,
sum(bfw_arr) AS bfw_arr,
sum(bfw_int) AS bfw_int,
sum(ytd_chg) AS ytd_chg,
sum(ytd_och) AS ytd_och
FROM (
-- BFWD Charges
SELECT src_bil_yer + 1 AS bil_yer,
src_acc_num AS acc_num,
des_ubsgch_key_num AS ubsgch_key_num,
src_trn_amt AS bfw_arr,
0 AS bfw_int,
0 AS ytd_chg,
0 AS ytd_och
FROM av_ub_tran
WHERE src_trn_cde <> 2601
UNION ALL -- BFWD Interest
SELECT src_bil_yer + 1 AS bil_yer,
src_acc_num AS acc_num,
des_ubsgch_key_num AS ubsgch_key_num,
0 AS bfw_arr,
src_trn_amt AS bfw_int,
0 AS ytd_chg,
0 AS ytd_och
FROM av_ub_tran
WHERE src_trn_cde = 2601
UNION ALL -- YTD Current Charges - Raised in the current year but NOT past due
SELECT src_bil_yer AS bil_yer,
src_acc_num AS acc_num,
des_ubsgch_key_num AS ubsgch_key_num,
0 AS bfw_arr,
0 AS bfw_int,
src_trn_amt AS ytd_chg,
0 AS ytd_och
FROM av_ub_tran
WHERE src_trn_cde = 2600
AND src_due_dte >= 'TODAY'
UNION ALL -- YTD Current Overdue Charges - Raised in the current year but PAST due
SELECT src_bil_yer AS bil_yer,
src_acc_num AS acc_num,
des_ubsgch_key_num AS ubsgch_key_num,
0 AS bfw_arr,
0 AS bfw_int,
0 AS ytd_chg,
src_trn_amt AS ytd_och
FROM av_ub_tran
WHERE src_trn_cde = 2600
AND src_due_dte < 'TODAY'
)
GROUP BY
bil_yer,
acc_num,
ubsgch_key_num