日期:2014-05-18  浏览次数:20752 次

表中数据整合
有表如下
部门编码 科目编码 预算数
0201022 6602001 100
0201022 6602001-01 20
0201022 6602001-02 80
0201033 6602003 0
0201033 6602003-01 20
...............
...............
...............
后面还很多数据

希望能按部门编码相加后杠的数,如6602001=6602001-01+6602001-02,加完后的表数据如下
部门编码 科目编码 预算数
0201022 6602001 200
0201022 6602001-01 20
0201022 6602001-02 80
0201033 6602003 20
0201033 6602003-01 20
................
................ 
后面还很多数据。。。

------解决方案--------------------
SQL code

update a
set a.number = (select sum(number) from tb where left(sno,len(a.sno)) = a.sno)
from tb a

------解决方案--------------------
如果编码的位数是固定的,可以用以下语句,如果不是固定的需要变通一下
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([部门编码] varchar(7),[科目编码] varchar(10),[预算数] int)
insert [tb]
select '0201022','6602001',100 union all
select '0201022','6602001-01',20 union all
select '0201022','6602001-02',80 union all
select '0201033','6602003',0 union all
select '0201033','6602003-01',20
go

update a
set a.预算数=a.预算数+b.预算数
from tb a
join
(select left(科目编码,7) as 科目编码,sum(预算数) as 预算数 
 from tb where len(科目编码)>7 
 group by left(科目编码,7) 
) b
on a.科目编码=b.科目编码


select * from tb
/**
部门编码    科目编码       预算数
------- ---------- -----------
0201022 6602001    200
0201022 6602001-01 20
0201022 6602001-02 80
0201033 6602003    20
0201033 6602003-01 20

(5 行受影响)
**/