日期:2014-05-16 浏览次数:20830 次
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
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