Alvaro Parra
Alvaro Parra

Reputation: 805

Mysql query sum values into multiple rows

I have this

id    value
-----!-----
 1      3
 2      3
 1      2
 1      1

i have tried using

SELECT id,sum(value) FROM table GROUP BY id 

but it shows something different.

   id   ! value
  --------------   
   1        6
   2        3 

And i want to add values based on their id's but keeping id's there

 id   ! value
--------------   
 1      6
 2      3
 1      6
 1      6

Please help Thank you

Upvotes: 1

Views: 2337

Answers (2)

Grisha Weintraub
Grisha Weintraub

Reputation: 7986

The naive approach would be :

select id, (select sum(value) from tbl where id = t1.id) value
from tbl t1

Upvotes: 1

peterm
peterm

Reputation: 92785

Are you looking for this?

SELECT t.id, q.value
  FROM Table1 t JOIN
(
  SELECT id, SUM(value) value
    FROM Table1
   GROUP BY id
) q ON t.id = q.id

Output:

| ID | VALUE |
|----|-------|
|  1 |     6 |
|  2 |     3 |
|  1 |     6 |
|  1 |     6 |

Here is SQLFiddle demo

Upvotes: 4

Related Questions