简体   繁体   English

MySQL每行总和

[英]Mysql each row sum

How can I get result like below with mysql? 我怎样才能得到如下结果与mysql?

> +--------+------+------------+
> | code   | qty  | total      |
> +--------+------+------------+
> |    aaa |   30 |         75 |
> |    bbb |   20 |         45 |
> |    ccc |   25 |         25 |
> +--------+------+------------+

total is value of the rows and the others that comes after this. total是行的值,其后是其他行。

You can do this with a correlated subquery -- assuming that the ordering is alphabetical: 您可以使用相关子查询来执行此操作-假设顺序是字母顺序的:

select code, qty,
       (select sum(t2.qty)
        from mytable t2
        where t2.code >= t.code
       ) as total
from mytable t;

SQL tables represent unordered sets. SQL表表示无序集。 So, a table, by itself, has no notion of rows coming after. 因此,表本身就没有后续行的概念。 In your example, the codes are alphabetical, so they provide one definition. 在您的示例中,代码是按字母顺序排列的,因此它们提供了一个定义。 In practice, there is usually an id or creation date that serves this purpose. 实际上,通常有一个ID或创建日期可满足此目的。

I would use join, imho usually fits better. 我会使用join,恕我直言通常更适合。

Data: 数据:

create table tab (
  code varchar(10),
  qty int
);

insert into tab (code, qty)
select * from (
  select 'aaa' as code, 30 as qty union
  select 'bbb', 20 union
  select 'ccc', 25
) t

Query: 查询:

select t.code, t.qty, sum(t1.qty) as total
from tab t
join tab t1 on t.code <= t1.code
group by t.code, t.qty
order by t.code

The best way is to try both queries (my and with subquery that @Gordon mentioned) and choose the faster one. 最好的方法是尝试两个查询(我的查询和@Gordon提到的子查询)并选择速度更快的查询。

Fiddle: http://sqlfiddle.com/#!2/24c0f/1 小提琴: http ://sqlfiddle.com/#!2/24c0f/1

Consider using variables. 考虑使用变量。 It looks like: 看起来像:

select code, qty, (@total := ifnull(@total, 0) + qty) as total
    from your_table
    order by code desc

...and reverse query results list afterward. ...然后反向查询结果列表。

If you need pure SQL solution, you may compute sum of all your qty values and store it in variable. 如果您需要纯SQL解决方案,则可以计算所有qty值的总和并将其存储在变量中。

Also, look at: Calculate a running total in MySQL 另外,请查看: 计算MySQL中的运行总计

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM