如果可以的话,我想避免使用嵌套的选定语句(我怀疑我会遇到性能问题)。我正在尝试从金融交易表中获取每种交易类型的总数。我猜我可以使用同一张表中的多个选择,但我的 '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