答案 0 :(得分:2)
按如下所示设置示例数据:
CREATE TABLE #Inventory (
ReportingDate date NOT NULL,
Purchases int NOT NULL
);
GO
INSERT INTO #Inventory (ReportingDate,Purchases)
VALUES
('20181101',77000),
('20181102',100000),
('20181108',0),
('20181109',0),
('20181201',164000),
('20181208',0),
('20181215',0);
GO
对于SQL Server 2008和更早版本,请尝试以下操作:
WITH Pre2012Inv AS (
SELECT *,
(SELECT SUM(Purchases) FROM #Inventory iv WHERE iv.ReportingDate <= i.ReportingDate) AS EndingInventory,
ROW_NUMBER() OVER(ORDER BY ReportingDate ASC) AS RowNum
FROM #Inventory i
)
SELECT p.ReportingDate,
ISNULL(p1.EndingInventory,0) AS BeginningInventory,
p.Purchases,
p.EndingInventory
FROM Pre2012Inv p
LEFT JOIN Pre2012Inv p1 ON p1.RowNum = p.RowNum-1;
对于SQL Server 2012和更高版本,请尝试以下操作:
WITH Inv AS (
SELECT *,
SUM(Purchases) OVER (ORDER BY ReportingDate ASC ROWS UNBOUNDED PRECEDING) AS EndingInventory
FROM #Inventory
)
SELECT ReportingDate,
LAG(EndingInventory,1,0) OVER (ORDER BY ReportingDate ASC) AS BeginningInventory,
Purchases,
EndingInventory
FROM Inv;