这有个示例,但我不知道怎样运用到我这个实例中。 declare @dt datetime,@pid char(3) set @dt='2004-01-08' set @pid='001' declare @p table ( pid char(3),iodt datetime, qty int) insert @p select '001', '2004-01-01', 10 union select '001', '2004-01-03', 6 union select '001', '2004-01-04', -1 union select '001', '2004-01-05', 5 union select '001', '2004-01-07', -2 select pid,库龄,iodt, case when qty>数量 then 数量 else qty end as 数量 from ( select pid,datediff(day,iodt,@dt) as 库龄, iodt,qty, ( select isnull(sum(qty),0) from @p where pid=@pid and iodt<=@dt and (iodt<=a.iodt or (iodt>a.iodt and qty<0)) ) as 数量 from @p a where pid=@pid and iodt<=@dt and qty>0 ) b where 数量>0 order by iodt desc |