mysql 使用列的总和来获取每个组的总金额
mysql using sum for a column to get total amount for each group
这是table订单中的数据。
谁能帮我做统计工作?
------------------------------
编号 | order_amount |创建时间
------------------------------
1 | 10 | 1513605522
2 | 20 | 1513605523
3 | 30 | 1513605524
4 | 40 | 1513605525
------------------------------
这是我需要的输出
------------------------------
total_income |创建时间
------------------------------
10 | 1513605522
30 | 1513605523
60 | 1513605524
100 | 1513605525
------------------------------
这是我的 sql 声明,它没有给我想要的东西。
select sum(order_amount) as total_income from order group by create time;
顺便提一句。是否有可能产生输出......
任何帮助对我来说意义重大。非常感谢。
在 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 最终支持window功能,因此可以使用该版本中的标准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;
这是table订单中的数据。
谁能帮我做统计工作?
------------------------------ 编号 | order_amount |创建时间 ------------------------------ 1 | 10 | 1513605522 2 | 20 | 1513605523 3 | 30 | 1513605524 4 | 40 | 1513605525 ------------------------------这是我需要的输出
------------------------------ total_income |创建时间 ------------------------------ 10 | 1513605522 30 | 1513605523 60 | 1513605524 100 | 1513605525 ------------------------------这是我的 sql 声明,它没有给我想要的东西。
select sum(order_amount) as total_income from order group by create time;
顺便提一句。是否有可能产生输出......
任何帮助对我来说意义重大。非常感谢。
在 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 最终支持window功能,因此可以使用该版本中的标准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;