取消组合SUM和GROUP BY

时间:2014-12-17 17:34:56

标签: mysql sum

我知道如何在MySQL中执行SUM但是如何添加这样的列(取消组合?)

CREATE TABLE Table1
    (`id` int, `price` int)
;

INSERT INTO Table1
    (`id`, `price`)
VALUES
    (1,10),
    (1, 10),
    (2, 20),
    (2, 20),
    (3, 30),
    (3, 31)
;

ID会像'类别ID'一样思考。 我想要这个:

ID    price    sum
--------------------
 1     10      20 <- or nothing if it's not to hard
 1     10      20
 2     20      40 
 2     20      40
 3     30      61
 3     31      61

不是这个:

ID    price    sum
--------------------
 1     10      20
 2     20      40
 3     30      61

sql:

SELECT id, SUM(price)FROM Table1 GROUP BY id

http://sqlfiddle.com/#!2/34fbe/1

1 个答案:

答案 0 :(得分:2)

您可以使用子查询:

select t.*, tt.sumprice
from table1 t join
     (select id, sum(price) as sumprice
      from table1 t
      group by id
     ) tt
     on t.id = tt.id;