求和多行

时间:2012-10-12 12:23:18

标签: mysql sql

所以我有一张这样的表:

id    mod    n1    n2    n3
1     1      1     1
1     2            2
1     3                  3
2     1      1
2     2            2
3     1      1

我想将特定id的所有行的每个值总结为列调用总数,但我不想将id组合在一起,因为它们具有不同的mod号。我想要一个这样的结果:

id    mod   total
1     1     7
1     2     7
1     3     7
2     1     3
2     2     3
3     1     1

我不能使用group by,因为它会给我每个行的总数。我如何实现我想要的结果?

5 个答案:

答案 0 :(得分:7)

你可以这样做:

SELECT `table`.`id`, `mod`, mySum
FROM `table` 
JOIN (SELECT `id`, SUM(n1) + SUM(n2) + SUM(n3) AS mySum
        FROM `table` GROUP BY `id`) as grpTable
ON `table`.`id` = `grpTable`.`id`

不确定这个的表现虽然......

答案 1 :(得分:2)

尝试:

select t.id, t1.mod, t.total
from tab t1
join (select id, sum( IFNULL(n1,0)+ IFNULL(n2,0)+ IFNULL(n3,0)) as total
      from tab 
      group by id) t on t.id=t1.id

答案 2 :(得分:1)

SELECT `id`, `mod`, (SUM(n1) + SUM(n2) + SUM(n3)) AS total
FROM `table` 
 GROUP BY `id`,`mod`

答案 3 :(得分:1)

第二个答案是正确的,所需要的只是正确调用ifnull

select t.id, t1.mod, t.total
from test.source t1
join (select id, sum( IFNULL(n1,0)+ IFNULL(n2,0)+ IFNULL(n3,0)) as total
      from test.source 
      group by id) t on t.id=t1.id

答案 4 :(得分:0)

这对你有用。在Oracle工作。检查是否需要在mysql中更改关键字。

SELECT x.id, x.mod, y.sum
  FROM table x,
       (SELECT id, sum(nvl(n1, 0) + nvl(n2, 0) + nvl(n3, 0)) sum
          FROM table
         GROUP BY id) y
 WHERE x.id = y.id;