答案 0 :(得分:0)
假设您想要每个仓库中每个产品的运行余额,这应该可以帮助您开始实现您想要的目标。如果您需要以不同的方式汇总产品和仓库,我会留下让您弄清楚。
这里的关键部分是在order by
窗口函数子句中使用over
。这样做是sum
所有行,直到当前开启,按InvoiceDate
顺序:
declare @t table(InvoiceDate date,InvoiceNo nvarchar(20),ProductId int,WareHouseId int,StockIn int, StockOut int);
insert into @t values('20180211','11218',2,2,100,0),('20180301','march18',1002,2,30,0),('20180701','july2018',1003,2,50,0),('20180701','july2018',1002,2,100,0),('20180301','SI-00001',1002,2,0,20),('20180301','SI-00002',1002,2,0,5),('20180317','20180317',1003,3009,50,0),('20180317','20180317',1010,3009,30,0),('20180317','20180317',1012,3009,25,0),('20180301','SI-18-03-1',1002,3009,0,20),('20180301','ST-18-03-01',1003,3009,50,0);
select t.WareHouseId
,t.InvoiceNo
,t.ProductId
,t.StockIn
,t.StockOut
,sum(t.StockIn) over (partition by t.WareHouseID, t.ProductId order by t.InvoiceDate, t.InvoiceNo)
-sum(t.StockOut) over (partition by t.WareHouseID, t.ProductId order by t.InvoiceDate, t.InvoiceNo) as Balance
from @t as t
order by t.WareHouseId
,t.ProductId
,t.InvoiceDate
,t.InvoiceNo;
输出:
+-------------+-------------+-----------+---------+----------+---------+
| WareHouseId | InvoiceNo | ProductId | StockIn | StockOut | Balance |
+-------------+-------------+-----------+---------+----------+---------+
| 2 | 11218 | 2 | 100 | 0 | 100 |
| 2 | march18 | 1002 | 30 | 0 | 30 |
| 2 | SI-00001 | 1002 | 0 | 20 | 10 |
| 2 | SI-00002 | 1002 | 0 | 5 | 5 |
| 2 | july2018 | 1002 | 100 | 0 | 105 |
| 2 | july2018 | 1003 | 50 | 0 | 50 |
| 3009 | SI-18-03-1 | 1002 | 0 | 20 | -20 |
| 3009 | ST-18-03-01 | 1003 | 50 | 0 | 50 |
| 3009 | 20180317 | 1003 | 50 | 0 | 100 |
| 3009 | 20180317 | 1010 | 30 | 0 | 30 |
| 3009 | 20180317 | 1012 | 25 | 0 | 25 |
+-------------+-------------+-----------+---------+----------+---------+