请问我在同一张表中,有序号,产品编号,数量三个字段,我想把编号相同的记录的数量累加起来,请问怎么办?
如:
序号 编号 数量
1 a01 20
2 a02 10
3 a01 15
4 a01 30
5 a02 41
如上所示,我这张表有两千多条数据,编号相同的也有300多条,我就想把数据累加成
序号 编号 数量
1 a01 65
2 a02 51请问要这样的效果该怎么做?
如:
序号 编号 数量
1 a01 20
2 a02 10
3 a01 15
4 a01 30
5 a02 41
如上所示,我这张表有两千多条数据,编号相同的也有300多条,我就想把数据累加成
序号 编号 数量
1 a01 65
2 a02 51请问要这样的效果该怎么做?
create table T(序号 int, 编号 char(3), 数量 int)
insert T select 1, 'a01', 20
union all select 2, 'a02', 10
union all select 3, 'a01', 15
union all select 4, 'a01', 30
union all select 5, 'a02', 41select min(序号) as 序号, 编号, sum(数量) as 数量
from T
group by 编号--result
序号 编号 数量
----------- ---- -----------
1 a01 65
2 a02 51(2 row(s) affected)
create table T(序号 int, 编号 char(3), 数量 int)
insert T select 1, 'a01', 20
union all select 2, 'a02', 10
union all select 3, 'a01', 15
union all select 4, 'a01', 30
union all select 5, 'a02', 41update T set 数量=tmp.数量
from
(
select min(序号) as 序号, 编号, sum(数量) as 数量
from T
group by 编号
)tmp
where T.序号=tmp.序号select * from T--result
序号 编号 数量
----------- ---- -----------
1 a01 65
2 a02 51
3 a01 15
4 a01 30
5 a02 41(5 row(s) affected)
select min(序号) as 序号
from T
group by 编号
)
select * from T--result
序号 编号 数量
----------- ---- -----------
1 a01 65
2 a02 51(2 row(s) affected)
from
(select 序号,编号 from T)tem
where tem.序号<T.序号 and tem.编号=T.编号删除还可以这样,但想对于上面的有些麻烦!