3

私はmysqlで書かれた銀行データベースを持っています。生成グループごとのレコード/レポートに MySQL ピボット テーブルを使用しています。

これは、アカウント メンテナンス用のサンプル テーブルです。

 ----------------------------------------------------------------------------------
account_number   | description   | Transaction Amount | Balance  | transaction_date
----------------------------------------------------------------------------------
1021212              1             0                    0          2013-04-02
1021213              1             100                 100         2013-04-01
1021212              1             1000                1000        2013-04-02
1021213              1             100                 200         2013-04-01
1021214              1             500                 500         2013-04-02
1021212              2             100                 900         2013-04-09

日次 (月次) のトランザクションを表示する完全なレポートを実行する必要があります。

これは私が必要とするレポート形式です。

-----------------------------------------------------------------------------------
account_number   | init_balance   | total_banking | total_withdraw | final_balance
----------------------------------------------------------------------------------
1021212              0               1000            100                900
1021213              100             100             0                  200
1021214              0             500             0                    600

ピボット テーブル クエリを使用してこのレポートを生成しようとしていますが、初期残高フィールドと最終残高フィールドを除くすべての情報を取得できました。

これは私のサンプルクエリです。

SELECT account_number,
**xxxxxxxxxx AS init_balance,**
SUM(CASE WHEN m.description = '1' THEN m.amount END) AS total_banking,
SUM(CASE WHEN m.description = '2' THEN m.amount END) AS total_withdraw,
**xxxxxxxxxx AS final_balance**
FROM account
WHERE transaction_date BETWEEN '2013-04-01' AND '2013-04-30'
GROUP BY account_number
ORDER BY account_number

誰かが助けてくれるなら、結果をグループ化してテーブルの最初と最後の行を取得するためのピボットテーブルを書くパターンを教えてください。

4

2 に答える 2

1

試す

CASE WHEN MIN(record_id_field) THEN Balance   END AS initial_amount

CASE WHEN MAX(record_id_field) THEN Balance   END AS final_amount
于 2013-04-22T13:35:07.840 に答える
1

あなたはそのようなものが必要です:

    SELECT
    m.account_number,
    SUM(IF(id = t.min_id, balance, 0)) AS init_balance,
    SUM(CASE WHEN m.description = '1' THEN m.amount END) AS total_banking,
    SUM(CASE WHEN m.description = '2' THEN m.amount END) AS total_withdraw,
    SUM(IF(id = t.max_id, balance, 0)) AS final_balance
FROM
    account m
INNER JOIN
    (
        SELECT
            account_number,
            MIN(id) AS min_id,
            MAX(id) AS max_id
        FROM
            account
        GROUP BY account_number
    ) AS t
ON
    m.account_number = t.account_number
WHERE
    transaction_date BETWEEN '2013-04-01' AND '2013-04-30'
GROUP BY
    account_number
ORDER BY
    account_number
于 2013-04-22T13:45:14.563 に答える