6

所以我有一张这样的桌子:

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,因为它会给我每个单独行的总数。如何达到我想要的结果?

4

5 回答 5

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`

虽然不确定这个的性能......

于 2012-10-12T12:26:55.787 回答
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
于 2012-10-12T12:27:53.913 回答
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
于 2012-10-12T13:55:32.797 回答
1
SELECT `id`, `mod`, (SUM(n1) + SUM(n2) + SUM(n3)) AS total
FROM `table` 
 GROUP BY `id`,`mod`
于 2012-10-12T12:32:25.480 回答
0

这应该适合你。在甲骨文工作。检查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;
于 2012-10-12T12:48:38.437 回答