如何在MySQL中获取当前日期的行起始值和结束值?

时间:2019-04-19 11:23:00

标签: mysql

表1:用户

user_id | user_name |user_type|
--------+-----------+---------+
 1      |   Noah    |  1      |
 2      |   Liam    |  3      |
 3      |   William |  3      |
 4      |   Benjamin|  3      |
 5      |   Jacob   |  2      |
--------+----+-------+--------+

表2:充值

id |recharged_by| status |amount| balance| debit|credit|created_at        
---+------------+--------+------+--------+------+------+-------------------
 1 |     2      | failed |  200 | 1000   |0     | 200  |2019-04-19 09:50:01
 2 |     3      | success|  100 | 500    |100   |  0   |2019-04-19 09:55:20
 3 |     3      | failed |  150 | 500    |0     | 150  |2019-04-19 10:00:00
 4 |     4      | failed |  200 | 2000   |0     | 200  |2019-04-19 11:30:40
 5 |     2      | success|  250 | 750    |250   |  0   |2019-04-19 03:50:00
 6 |     4      | pending|  300 | 1700   |300   |  0   |2019-04-19 06:00:00
---+-------------+------------+----------+------+------+-------------------

想要的结果:

user_name|user_type|opening_bal|success_total |failed_total|closing_bal|
---------+--------+-----------+---------------+------------+-----------+
 Liam    |    3   |   1000    |  250          |   200      |   750     |
 William |    3   |   500     |  100          |   150      |   500     |
 Benjamin|    3   |   2000    |  0            |   200      |   1700    |
---------+--------+-----------+---------------+------------+-----------+

我的查询:

SELECT u.user_name,u.user_type,r.created_at,

(CASE WHEN CAST(r.created_at AS DATE)= CURRENT_DATE THEN r.balance_amount ELSE 0 END) opening_balance,
(CASE WHEN CAST(r.created_at AS DATE)= CURRENT_DATE THEN r.balance_amount ELSE 0 END) closing_balance,

SUM(CASE WHEN r.status = 'success' THEN r.recharge_amount ELSE 0 END) success_total, 
SUM(CASE WHEN r.status = 'failed' THEN r.recharge_amount ELSE 0 END) failed_total,
SUM(CASE WHEN r.status = 'pending' THEN r.recharge_amount ELSE 0 END) pending_total,

COALESCE((r.debited_amount), '0') AS debit_total,
COALESCE((r.credited_amount), '0') AS credit_total

FROM recharges r LEFT JOIN user u ON r.recharge_by = u.user_id WHERE CAST(r.created_at AS DATE)= CURRENT_DATE AND r.api_channel = 4 GROUP BY u.user_id

这里的期初余额是当天的期初余额,期末余额是当天的期末余额,我还需要总成功金额,总失败金额,总未决金额,总借方金额,贷方金额。

0 个答案:

没有答案