获取库存运行余额

时间:2015-10-29 07:37:07

标签: sql sql-server-2008-r2 cursor

所以这是问题所在。我有以下临时表

+------------+---------+-----------+-----+-----+
| Date       | Name    | Reference | In  | Out |
+------------+---------+-----------+-----+-----+
| 2015-10-28 | Sample1 | Invoice1  | 100 | 0   |
+------------+---------+-----------+-----+-----+
| 2015-10-29 | Sample1 | Release1  | 0   | 100 |
+------------+---------+-----------+-----+-----+
| 2015-10-29 | Sample1 | Invoice2  | 200 | 0   |
+------------+---------+-----------+-----+-----+
| 2015-10-29 | Sample1 | Invoice3  | 300 | 0   |
+------------+---------+-----------+-----+-----+
| 2015-10-29 | Sample1 | Release2  | 0   | 300 |
+------------+---------+-----------+-----+-----+

我需要计算运行余额。这已经被正确订购

+------------+---------+-----------+-----+-----+---------+
| Date       | Name    | Reference | In  | Out | Balance |
+------------+---------+-----------+-----+-----+---------+
| 2015-10-28 | Sample1 | Invoice1  | 100 | 0   | 100     |
+------------+---------+-----------+-----+-----+---------+
| 2015-10-29 | Sample1 | Release1  | 0   | 100 | 0       |
+------------+---------+-----------+-----+-----+---------+
| 2015-10-29 | Sample1 | Invoice2  | 200 | 0   | 200     |
+------------+---------+-----------+-----+-----+---------+
| 2015-10-29 | Sample1 | Invoice3  | 300 | 0   | 500     |
+------------+---------+-----------+-----+-----+---------+
| 2015-10-29 | Sample1 | Release2  | 0   | 300 | 200     |
+------------+---------+-----------+-----+-----+---------+

目前正在使用Cursor,但我不确定这是否是正确的实现。我每次需要报告时都会调用此过程,因此可能存在性能问题

更新

找到了另一种方法。这比使用游标还是WITH语句更好?

DECLARE @RunningBalance decimal(18,2)

SET @RunningBalance = 0

UPDATE @StockInvetoryReport
SET @RunningBalance= Balance = ( @RunningBalance + [In] ) - [Out] 
OPTION (FORCE ORDER);

SELECT * FROM @StockInvetoryReport

1 个答案:

答案 0 :(得分:0)

创建一个子查询,为您的数据提供不同的id / RowNo。然后在CTE中使用子查询,方法是引用它两次并确保将它们连接到Name和distinctid列上,如图所示。

;WITH mytable AS
(SELECT 
    Date
    ,Name
    ,Reference
    ,In
    ,Out
    ,ROW_NUMBER() OVER (ORDER BY Date,Reference) AS RowNo
)
SELECT 
    a.Date
    ,a.Name
    ,a.Reference
    ,a.In
    ,a.Out
    ,SUM(b.In) - SUM(b.Out) Balance
FROM   
    mytable a,
    mytable b
WHERE 
    b.RowNo <= a.RowNo
    AND b.Name = a.Name
GROUP BY 
    a.Date
    ,a.Name
    ,a.Reference
    ,a.In
    ,a.Out
    ,a.RowNo
ORDER BY 
    a.RowNo