读书人

诚心求算法有关问题

发布时间: 2012-01-16 23:36:51 作者: rapoo

诚心求算法问题。
我现在有进销存明细表,如下

业务类型 数量 发生后库存余额
入库 5 5
入库 9 14
销售 3 11
入库 4 15

其中“数量”字段,是肯定可以取到的,但“发生后库存余额”字段,请问哪位高手可以给个好方法?在此谢过。

[解决办法]
drop table detail
go
create table detail(业务类型 varchar(10),数量 int)
insert into detail
select '入库 ',5
union all select '入库 ',9
union all select '销售 ',3
union all select '入库 ',4

alter table detail add id int identity(1,1)

select 业务类型,数量,(select sum(case when 业务类型= '入库 ' then 数量 when 业务类型= '销售 ' then -数量 else 0 end) from detail t where detail.id> =t.id) as '发生后库存余额 '
from detail

/*
业务类型 数量 发生后库存余额
---------- ----------- -----------
入库 5 5
入库 9 14
销售 3 11
入库 4 15

(所影响的行数为 4 行)
*/

[解决办法]
--如果有id列,或者不想建表,可以用:

create table T(type varchar(10),num int, num1 int)
insert into T
select 'in ',5,null union all
select 'in ',9,null union all
select 'out ',3,null union all
select 'in ',4,null

declare @num int,@sum int
select @num=0,@sum=0
update T
set num1=@num+@sum,
@sum=@num+@sum,
@num=case when type= 'in ' then num else -num end

select * from T
/*
type num num1
---------- ----------- -----------
in 5 5
in 9 14
out 3 11
in 4 15
*/


drop table T
[解决办法]
----------------------------------------沟
declare @sum int
select @sum=0
update T
set num1=@sum,
@sum=(case when type= 'in ' then num else -num end)+@sum
[解决办法]
一定要有主

--drop table T

create table T(id int identity(1,1),type varchar(10),num int, num1 int)
insert into T
select 'in ',5,null union all
select 'in ',9,null union all
select 'out ',3,null union all
select 'in ',4,null

select * from T

select type,num,
last_money=(select sum(case when type= 'in ' then num else -num end) from T where id <=A.id)
from T A

--果
type num last_money
in55
in914
out311
in415

读书人网 >SQL Server

热点推荐