SQL Server:每日开始库存和结束库存报告

时间:2018-12-21 10:25:25

标签: sql-server sql-server-2008

我有以下数据

enter image description here

我想计算开始和结束的广告资源。公式为:期初库存+购买=期末库存。结果应该是这样:

enter image description here

是否可以使用T-SQL查询?

1 个答案:

答案 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;