1

可能であれば、ネストされた選択されたステートメントの使用を避けたいと思います (パフォーマンスの問題が発生すると思われます)。金融取引テーブルから取引の種類ごとに合計を取得しようとしています。同じテーブルから複数の選択を使用できると思いますが、「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
4

1 に答える 1

0

使用する RDBMS については触れていませんが、ほとんどの RDBMS にはCASE ステートメントがあります。あなたはそれを使用することができます。src_bil_yer + 1最初のサブクエリで使用し、それはgroup byフィールドであるため、とにかくネストされたクエリを使用する必要があります。次のクエリを試してください。

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 (
    SELECT src_bil_yer + 1 AS bil_yer,
        src_acc_num AS acc_num,
        des_ubsgch_key_num AS ubsgch_key_num,
        CASE WHEN src_trn_cde <> 2601 THEN src_trn_amt ELSE 0 END AS bfw_arr,
        CASE WHEN src_trn_cde = 2601 THEN src_trn_amt ELSE 0 END AS bfw_int,
        0 AS ytd_chg,
        0 AS ytd_och
    FROM av_ub_tran

    UNION ALL 
    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,
        CASE WHEN src_due_dte >= 'TODAY' THEN src_trn_amt ELSE 0 END AS ytd_chg,
        CASE WHEN src_due_dte <  'TODAY' THEN src_trn_amt ELSE 0 END AS ytd_och
    FROM av_ub_tran
    WHERE src_trn_cde = 2600
)
GROUP BY
    bil_yer,
    acc_num,
    ubsgch_key_num
于 2013-02-20T11:26:46.600 に答える