tb表:
月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 72月份:
名称 购进 销售
a 8 2
b 8 5
c 9 6
d 5 2
现要根据上面情况将tb表更新为月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 7
2 a 8 2 11 注:11=5(1月库存总数)+8(2月购进)-2(2月销售)
2 b 8 5 13
2 c 9 6 10
2 d 5 2 3
不知怎样用sql语句实现
月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 72月份:
名称 购进 销售
a 8 2
b 8 5
c 9 6
d 5 2
现要根据上面情况将tb表更新为月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 7
2 a 8 2 11 注:11=5(1月库存总数)+8(2月购进)-2(2月销售)
2 b 8 5 13
2 c 9 6 10
2 d 5 2 3
不知怎样用sql语句实现
if object_id('tempdb.dbo.#tb') is not null drop table #tb
create table #tb (月份 int,名称 varchar(1),购进 int,销售 int,库存总数 int)
insert into #tb
select 1,'a',10,5,5 union all
select 1,'b',12,2,10 union all
select 1,'c',15,8,7 union all
select 2,'a',8,2,null union all
select 2,'b',8,5,null union all
select 2,'c',9,6,null union all
select 2,'d',5,2,nullupdate t set 库存总数=(select sum(购进-销售) from #tb where 名称=t.名称 and 月份<=t.月份) from #tb t where 月份=2select * from #tb/*
月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 7
2 a 8 2 11
2 b 8 5 13
2 c 9 6 10
2 d 5 2 3
*/
if object_id('tempdb.dbo.#tb') is not null drop table #tb
create table #tb (月份 int,名称 varchar(1),购进 int,销售 int,库存总数 int)
insert into #tb
select 1,'a',10,5,5 union all
select 1,'b',12,2,10 union all
select 1,'c',15,8,7
if object_id('tempdb.dbo.#tb2') is not null drop table #tb2
create table #tb2 (名称 varchar(1),购进 int,销售 int)
insert into #tb2
select 'a',8,2 union all
select 'b',8,5 union all
select 'c',9,6 union all
select 'd',5,2insert into #tb select 2, a.*, a.购进-a.销售+isnull(b.库存总数,0) from #tb2 a left join #tb b on a.名称=b.名称 where b.月份=1select * from #tb/*
月份 名称 购进 销售 库存总数
1 a 10 5 5
1 b 12 2 10
1 c 15 8 7
2 a 8 2 11
2 b 8 5 13
2 c 9 6 10
2 d 5 2 3
*/
名称 购进 销售
a 8 2
b 8 5
c 9 6
d 5 2
是在另外一张表如tb2中统计出来的
insert into tb1 values(1 , 'a' ,10 , 5 ,5 )
insert into tb1 values(1 , 'b' ,12 , 2 ,10)
insert into tb1 values(1 , 'c' ,15 , 8 , 7)
create table tb2(名称 varchar(10) , 购进 int, 销售 int )
insert into tb2 values('a' ,8, 2 )
insert into tb2 values('b' ,8, 5 )
insert into tb2 values('c' ,9, 6 )
insert into tb2 values('d' ,5, 2 )
go--查询
select * from tb1
union all
select 月份 = 2 , 名称 , 购进 , 销售 , 库存总数 = 购进 - 销售 + isnull((select 库存总数 from tb1 where 名称 = tb2.名称),0) from tb2
order by 月份,名称--将数据插入tb1表
insert into tb1 select 月份 = 2 , 名称 , 购进 , 销售 , 库存总数 = 购进 - 销售 + isnull((select 库存总数 from tb1 where 名称 = tb2.名称),0) from tb2
select * from tb1 order by 月份,名称drop table tb1,tb2/*
月份 名称 购进 销售 库存总数
----------- ---------- ----------- ----------- -----------
1 a 10 5 5
1 b 12 2 10
1 c 15 8 7
2 a 8 2 11
2 b 8 5 13
2 c 9 6 10
2 d 5 2 3(所影响的行数为 7 行)
*/