mysql 按最后添加的日期获取总和和顺序

o8x7eapl  于 2022-12-17  发布在  Mysql
关注(0)|答案(1)|浏览(113)

使用以下查询计算总余额:

SELECT ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance,
cw.date_added as last_updated_date
FROM customer_wallet cw
LEFT JOIN customers c ON c.id = cw.cus_id
GROUP BY cw.cus_id
ORDER BY cw.date_added DESC

另外,使用order by date_added来获得最后添加的日期。但是,获得每个客户的第一个日期记录。我如何获得最后日期?
这是SQLFiddle:http://sqlfiddle.com/#!9/585fd2/1
在SQLFiddle中,如果运行查询,将得到2022-12-01T00:00:00Z作为最后更新日期。
如果你需要更多的澄清,请告诉我。

dgenwo3n

dgenwo3n1#

需要使用max函数

SELECT ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance, max(cw.date_added) as last_updated_date
FROM customer_wallet cw
LEFT JOIN customers c ON c.id = cw.cus_id
GROUP BY cw.cus_id
ORDER BY cw.date_added DESC

http://sqlfiddle.com/#!9/585fd2/2

相关问题