SQL2000:SQL语句求助
各位大神:SQL2000 表结构如下
ItemMon QtyBalQty
211-0012013-8-53
211-0012013-9-10-7
211-0012013-11-8-15
211-0022013-9-85
211-0022013-10-6-1
211-0022013-12-7-8
表按照Item和Mon排序
要求取得报表,对于同一个Item 当最前面的BalQty<0时,以后取Qty
ItemMon BalQty
211-0012013-8 3
211-0012013-9 -7
211-0012013-11 -8
211-0022013-9 5
211-0022013-10 -1
211-0022013-12 -7
求各位大神帮忙下,谢谢!
[解决办法]
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
211-002 2013-12 -7
(所影响的行数为 6 行)
*/