日期:2014-05-17 浏览次数:20460 次
DECLARE @a TABLE (Item VARCHAR(20),Mon VARCHAR(20),Qty INT,BalQty INT)
INSERT @a SELECT '211-001','2013-08',-5,3
UNION ALL SELECT '211-001','2013-09',-10,-7
UNION ALL SELECT '211-001','2013-11',-8,-15
UNION ALL SELECT '211-002','2013-09',-8,5
UNION ALL SELECT '211-002','2013-10',-6,-1
UNION ALL SELECT '211-002','2013-12',-7,-8
SELECT Item,
Mon,
BalQty=
CASE WHEN Mon>(SELECT MIN(Mon) FROM @a b WHERE Item=a.Item AND BalQty<0) THEN Qty ELSE BalQty END
FROM @a a
ORDER BY Item,Mon
--result
/*
Item Mon BalQty
-------------------- -------------------- -----------
211-001 2013-08 3
211-001 2013-09 -7
211-001 2013-11 -8
211-002 2013-09 5
211-002 2013-10 -1