0

How can I get result like below with 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.

ozer
  • 335
  • 1
  • 5
  • 13

3 Answers3

3

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. 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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

I would use join, imho usually fits better.

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.

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

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
0

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.

Also, look at: Calculate a running total in MySQL

Community
  • 1
  • 1
George Sovetov
  • 4,942
  • 5
  • 36
  • 57