日期:2014-05-17  浏览次数:20474 次

以下SQL语句写法
SQL2000+Win2003,求SQL语句

原始数据
物料      出库     返仓        时间
----------------------------------------------
A         1000      ---        19:20
B         1200      ---        19:23
A           --      700        19:30
A          700      ---        19:38
A           --      200        19:45
----------------------------------------------
要求知道每种物料每资领用后的耗用量

物料    出库           返仓        耗用
-------------------------------------------
A       1000           700         300
B       1200             0        1200
A        700           200         500
---------------------------------------

------最佳解决方案--------------------

--> 测试数据: @T
declare @T table (物料 varchar(1),出库 int,返仓 int,时间 varchar(5))
insert into @T
select 'A',1000,null,'19:20' union all
select 'B',1200,null,'19:23' union all
select 'A',null,700,'19:30' union all
select 'A',700,null,'19:38' union all
select 'A',null,200,'19:45'

select 
m.物料,m.出库,
isnull(n.返仓,0) as 返仓,
m.出库-isnull(n.返仓,0) as 耗用 
from 
(select *,(select count(1) from @T b where b.物料=a.物料 and b.时间<=a.时间) as no from @T a) m 
left join 
(select *,(select count(1) from @T b where b.物料=a.物料 and b.时间<=a.时间) as no from @T a) n 
on m.物料=n.物料 and m.no=n.no-1 where m.出库 is not null

/*
物料   出库          返仓          耗用
---- ----------- ----------- -----------
A    1000        700         300
B    1200        0           1200
A    700         200         500

(3 row(s) affected)
*/


------其他解决方案--------------------
你应该是按时间来分组统计的吧?

要不然你组合的依据是什么?