![](/img/trans.png)
[英]How to sum the values in a column based on another column or different group?
[英]Sum the values of a column based on a group of values from another column
我有一张表格,其中每笔transaction
都与给定price
相关联。 像这样:
transaction price
1 10
2 20
3 30
5 50
6 10
10 10
23 10
24 10
25 10
26 10
27 10
我正在尝试找到一种基于特定交易或一组交易对price
进行求和的方法。 查询的结果将是这样的:
transaction price
1-3 60
5-6 60
10 10
23-27 50
这样,我可以知道对于事务1到事务3,结果是60,依此类推。 您能指出正确的方向以使用MySQL进行此操作吗?
由于mysql不支持窗口功能,因此我们必须为您的表创建自己的组排名,然后再创建另一个查询以对结果进行操作。
select if(count(transaction) = 1, transaction, concat(min(transaction), '-', max(transaction))) transactions, sum(price) price
from (
select if(`transaction` = @prev + 1,
if(@prev := `transaction`, @rank, @rank),
if(@prev := `transaction`, @rank := @rank + 1, @rank := @rank + 1)
) gr,
`transaction`,
price
from table1, (select @rank := 1, @prev := 0) q
order by `transaction` asc
) q
group by gr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.