日期:2014-05-16  浏览次数:20783 次

急:请教 统计同一个物件不同时间的剩余值(这个值是累加的)
我有这样一张表
CREATE TABLE [dbo].[MontlyMaterial](
[ID] [uniqueidentifier] NOT NULL,
[MaterialID] [tinyint] NOT NULL,
[InCount] [int] NULL,
[OutCount] [int] NULL,
[RecordDate] [date] NULL
)
  Insert [Farms].[dbo].[MonthlyMaterial]
  select NEWID(),1, 123,100, GETDATE() union all
  select NEWID(),2, 123,101, GETDATE() union all
  select NEWID(),3, 123,123, GETDATE() union all
  select NEWID(),1, 223,100, GETDATE()-30 union all
  select NEWID(),2, 323,200, GETDATE()-30 union all
  select NEWID(),3, 323,300, GETDATE()-30 union all
  select NEWID(),1, 223,150, GETDATE()-60 union all
  select NEWID(),2, 163,110, GETDATE()-60 union all  
  select NEWID(),3, 173,150, GETDATE()-60 union all
  select NEWID(),1, 143,130, GETDATE()-90 union all
  select NEWID(),2, 118,100, GETDATE()-90 union all
  select NEWID(),3, 923,800, GETDATE()-90 

我想得到剩余的材料,即@unUsedCount = @InCount - @OutCount,但是同一材料的剩余是每个月累加的

我是这样写的,但是得不到我想要的结果
 
  USE Farms 
  GO
  SELECT MaterialID,InCount,OutCount,MonthDate from [MonthlyMaterial]
  order by MaterialID,MonthDate
  
  declare @result
  Table(MaterialID tinyint,InCount INT,OutCount INT,unUsedCount INT,MonthDate date);
  
  Declare @PreMaterialID tinyint, @MaterialID tinyint,@PreInCount INT,@PreOutCount INT,@PreMonthDate date,@InCount INT,@OutCount INT,
  @unUsedCount INT,@MonthDate date;
  
  Declare C CURSOR  FAST_FORWARD FOR 
SELECT MaterialID,InCount,OutCount,MonthDate from MonthlyMaterial order by MaterialID,MonthDate
Open C
FETCH NEXT FROM C INTO @MaterialID,@InCount,@OutCount,@MonthDate
SELECT @PreMaterialID = @MaterialID,@PreInCount = @InCount,@PreOutCount=@OutCount,@unUsedCount=0,@PreMonthDate=@MonthDate;
WHILE  @@FETCH_STATUS=0
BEGIN

IF @PreMonthDate<>@MonthDate
BEGIN
IF @PreMaterialID <> @MaterialID
SET @unUsedCount = @PreInCount - @PreOutCount
ELSE
SET @unUsedCount = @unUsedCount + (@PreInCount - @PreOutCount)
INSERT INTO @result VALUES(@PreMaterialID,@PreInCount,@PreOutCount,@unUsedCount,@PreMonthDate)
SELECT  @PreMaterialID = @MaterialID,@PreInCount = @InCount,@PreOutCount=@OutCount,@unUsedCount=@unUsedCount ,@PreMonthDate=@MonthDate;

END

FETCH NEXT FROM C INTO @MaterialID,@InCount,@OutCount,@MonthDate
END
IF @PreMaterialID IS NOT NULL

INSERT INTO @result VALUES(@PreMaterialID,@PreInCount,@PreOutCount,@unUsedCount,@PreMonthDate);
CLOSE C;
DEALLOCATE C;

SELECT * FROM @resu