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

You need something like that:

    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 回答
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 回答