MySQL数据透视表获取分组记录中的第一行和最后一行

时间:2013-04-22 13:08:45

标签: php mysql sql mysqli

我有在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

如果有人可以提供帮助,请告诉我编写数据透视表的模式,以获取表格的第一行和最后一行以及分组结果。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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