1

I have sample data with table name catdog

  | No  | id | data |
      1     1   4000    
      2     2   300    
      3     3   100
      4     1   400
      5     2   30
      6     3   10
      7     1   40
      8     2   3
      9     3   1

I want the result like this:

| No  | id | data | totaldata |
  1     1   4000    4000
  2     2   300     300
  3     3   100     100
  4     1   400     4400      --------> 4000 + 400 on id
  5     2   30      330       --------> 300 + 30 on id
  6     3   10      110       --------> 100 + 10 on id
  7     1   40      4440      --------> 4000 + 400 + 40 on id
  8     2   3       333       --------> 300 + 30 + 1 on id
  9     3   1       111       --------> 100 + 10 + 1 on id

Sum if field No is same. How to write a mysql query for my case?

very very thank you so much GurV

1 Answer 1

1

Try this:

select no, id, data, c_data from (
select t1.*,
    @data := case when @id = id then @data + data else data end c_data,
    @id := id
from
(select * from catdog
order by id, No) t1
cross join (select @id := -1, @data := 0) t2) t
order by no;

It uses user defined variables to keep track of sum till now for each id

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.