mysql使用sum的列来获取每个组的总金额
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql使用sum的列来获取每个组的总金额相关的知识,希望对你有一定的参考价值。
这是表格订单中的数据。
有没有人可以帮我做统计工作?
------------------------------- id | order_amount | createtime ------------------------------- 1 | 10 | 1513605522 2 | 20 | 1513605523 3 | 30 | 1513605524 4 | 40 | 1513605525 -------------------------------This is the output what I need
------------------------------- total_income | createtime ------------------------------- 10 | 1513605522 30 | 1513605523 60 | 1513605524 100 | 1513605525 -------------------------------this is my sql statement, it doesn't give me what i want.
select sum(order_amount) as total_income from order group by create time;
BTW. Is it possible to produce the output....
Any help means a lot to me. Many thanks.
答案
在mysql中,您可以使用相关子查询来执行此操作:
select o.*,
(select sum(o2.order_amount)
from orders o2
where o2.createtime <= o.createtime
) as running_amount
from orders o;
另一个选择 - 使用非标准SQL - 是使用变量:
select o.*, (@s := @s + o.order_amount) as running_amount
from (select o.*
from orders o
order by createtime
) o cross join
(select @s := 0) params;
请注意,子查询仅在更新版本的MySQL中需要。
实际上,MySQL 8.0最终支持窗口函数,因此可以使用该版本中的标准SQL来完成:
select o.*, sum(o.order_amount) over (order by o.createtime) as running_amount
from orders o;
另一答案
您可以使用:
set @amt := 0;
select @amt := @amt + order_amount as total_income, createtime
from order
order by createtime asc;
以上是关于mysql使用sum的列来获取每个组的总金额的主要内容,如果未能解决你的问题,请参考以下文章