如何计算打开和关闭数量余额SQL Server

时间:2011-07-15 15:37:00

标签: sql sql-server tsql

我有以下表格结构

TransactionDate   Item  RecQty  IssueQty

1-jun-2011         A      10      0
2-jun-2011         A      15      0
3-jun-2011         A      20      0
4-jun-2011         A       0     20
4-jun-2011         A       0     20

我希望结果在特定日期,即2011年6月2日

 Item    Opening     RecQty  IssueQty  BalanceQty
  A       10            15     0         25

并于2011年1月4日

 Item    Opening     RecQty  IssueQty  BalanceQty
  A       45            0     40         5

1 个答案:

答案 0 :(得分:1)

我将至少假设SQL Server 2005.将来,请指定/标记您需要支持的最低版本的问题。

CREATE TABLE #x
(
    TransactionDate SMALLDATETIME,
    Item CHAR(1), RecQty INT, IssueQty INT
);

INSERT #x SELECT '20110601','A',10,0
UNION ALL SELECT '20110602','A',15,0
UNION ALL SELECT '20110603','A',20,0
UNION ALL SELECT '20110604','A',0,20
UNION ALL SELECT '20110604','A',0,20;

DECLARE @StartDate SMALLDATETIME = '20110601', 
        @Date      SMALLDATETIME = '20110602';

WITH x(Item, prevR, prevI, curR, curI) AS
(
    SELECT 
        Item,
        SUM(CASE WHEN TransactionDate < @Date THEN RecQty ELSE 0 END),
        SUM(CASE WHEN TransactionDate < @Date THEN IssueQty ELSE 0 END),
        SUM(CASE WHEN TransactionDate = @Date THEN RecQty ELSE 0 END),
        SUM(CASE WHEN TransactionDate = @Date THEN IssueQty ELSE 0 END)
    FROM #x WHERE TransactionDate BETWEEN @StartDate AND @Date
    GROUP BY Item
)
SELECT 
    Item,
    Opening = prevR - prevI,
    RecQty = curR,
    IssueQty = curI,
    BalanceQty = (prevR - prevI) + (curR - curI)
FROM x;

DROP TABLE #x;