在我的项目中,我需要将相同类型和相同参数的所有行的大小相加,其他只是保持不变。例如,我有这样一张桌子:
id | type | ammount | param1 | param2 | param3
1 | 1 | 5 | 1 | 3 | 2
2 | 1 | 20 | 2 | 3 | 2
3 | 1 | 21 | 1 | 3 | 2
4 | 2 | 10 | 1 | 3 | 2
5 | 2 | 3 | 1 | 2 | 1
我想要达到的结果是:
type | sum of ammount | param1 | param2 | param3
1 | 26 | 1 | 3 | 2
1 | 20 | 2 | 3 | 2
2 | 10 | 1 | 3 | 2
2 | 3 | 1 | 2 | 1
正如您所看到的,ID为1和3的行具有相加的ammounts,因为它们具有相同的类型且所有参数(param1和param2与param3)相同。我怎样才能做到这一点?我使用mysql。
提前谢谢。
Kalreg。
答案 0 :(得分:0)
使用“group by”子句:
use test;
create table Testsum(id int, type int, ammount int, param1 int, param2 int, param3 int);
insert Testsum(id, type, ammount, param1, param2, param3)
values(1, 1, 5, 1, 3, 2),
(2, 1, 20, 2, 3, 2),
(3, 1, 21, 1, 3, 2),
(4, 2, 10, 1, 3, 2),
(5, 2, 3, 1, 2, 1);
/*
id | type | ammount | param1 | param2 | param3
1 | 1 | 5 | 1 | 3 | 2
2 | 1 | 20 | 2 | 3 | 2
3 | 1 | 21 | 1 | 3 | 2
4 | 2 | 10 | 1 | 3 | 2
5 | 2 | 3 | 1 | 2 | 1
*/
select type, sum(ammount) as ammount, param1, param2, param3
from Testsum
group by type, param1, param2, param3;
结果:
type,ammount,param1,param2,param3
1,26,1,3,2
1,20,2,3,2
2,3,1,2,1
2,10,1,3,2
可能最高ID有助于:
select max(id) as id, type, sum(ammount) as ammount, param1, param2, param3
from Testsum
where ammount is not null or ammount <> 0
group by type, param1, param2, param3 ;
或指定min(id)而不是max(id)的最低ID。