Mysql 多行求和
我有一张这样的桌子:Mysql 多行求和,mysql,sql,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 mod total 1 1 7 1 2 7 1 3 7 2 1 3 2 2 3 3
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 mod total
1 1 7
1 2 7
1 3 7
2 1 3
2 2 3
3 1 1
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`
我想把一个特定id的所有行的每个值汇总成一个列调用总数,但我不想把id分组在一起,因为它们有不同的mod number。我想要这样的结果:
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 mod total
1 1 7
1 2 7
1 3 7
2 1 3
2 2 3
3 1 1
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`
我不能使用group by,因为它只会给出每行的总数。如何实现我想要的结果?您可以这样做:
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 mod total
1 1 7
1 2 7
1 3 7
2 1 3
2 2 3
3 1 1
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`
但不确定此功能的性能…请尝试:
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
这应该对你有用。在甲骨文工作。检查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;
第二个答案是正确的,只需要正确调用
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
我不明白total列背后的计算方法?使用Windows函数,您可以得到一个单行查询来返回所需的结果集。不幸的是,MySQL不支持它们。@njzk2:如果您查看第一个表,您将看到total与
id
中所有项目的total匹配。mod似乎没有任何实际影响,因此第二个表中的每条记录的total
似乎都是一个冗余列。@njzk2检查所有1 ID的值你知道7是怎么来的了。。前三行。当mod
列不传递任何信息时,为什么要在结果集中保留该列?我认为这需要表
。select子句中id前面的前缀