你可以这样做:
;WITH WithClosingBalances
AS
(
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
([return] + rdj + rpo + xefr) -
(adj+iss+piss+tsfr) ClosingBalance,
ROW_NUMBER() OVER(PARTITION BY INVENTORYNAME
ORDER BY month) rownum
FROM table1
), WithOpeningBalances
AS
(
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
ClosingBalance,
ISNULL((SELECT ClosingBalance
FROM WithClosingBalances c2
WHERE c1.rownum - c2.rownum =1
), 0) OpeningBalance,
rownum
FROM WithClosingBalances c1
)
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
ClosingBalance,
OpeningBalance,
OpeningBalance + ClosingBalance AS CurrentMonthBalance
FROM WithOpeningBalances;
这会给你:
| STOCKNUMBER | INVENTORYNAME | YEAR | MONTH | ADJ | ISS | PISS | TSFR | RETURN | RDJ | RPO | XEFR | CLOSINGBALANCE | OPENINGBALANCE | CURRENTMONTHBALANCE |
------------------------------------------------------------------------------------------------------------------------------------------------------------
| alb001 | clinic1 | 2010 | 1 | 4 | 5 | 5 | 5 | 6 | 5 | 4 | 10 | 6 | 0 | 6 |
| alb001 | Clinic1 | 2010 | 2 | 10 | 2 | 2 | 3 | 3 | 4 | 4 | 4 | -2 | 6 | 4 |
| alb001 | Clinic1 | 2010 | 4 | 11 | 3 | 5 | 77 | 90 | 78 | 9 | 6 | 87 | -2 | 85 |
| alb001 | Clinic1 | 2010 | 5 | 10 | 2 | 2 | 3 | 3 | 4 | 4 | 4 | -2 | 87 | 85 |
这个查询是如何工作的?
我从您的问题中了解到,此查询将评估CURRENTMONTHBALANCE CLOSINGBALANCE
,OPENINGBALANCE, and
如下所示:
CLOSINGBALANCE
=
[return] + rdj + rpo + xefr) -
(adj+iss+piss+tsfr)
每个月。我假设每个月的表中的每条记录。
OPENINGBALANCE
: 是CLOSINGBALANCE
按库存名称分组的上个月。这是使用ROW_NUMBER() OVER(PARTITION BY InventoryName)
.
CURRENTMONTHBALANCE
=OpeningBalance + ClosingBalance
每条记录。
更新:JOIN
如果有多个月份的条目,您可以使用而不是相关子查询,如下所示:
;WITH WithClosingBalances
AS
(
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
([return] + rdj + rpo + xefr) -
(adj+iss+piss+tsfr) ClosingBalance,
ROW_NUMBER() OVER(PARTITION BY INVENTORYNAME
ORDER BY month) rownum
FROM table1
), WithOpeningBalances
AS
(
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
c1.ClosingBalance,
ISNULL(c2.ClosingBalance, 0) OpeningBalance
FROM WithClosingBalances c1
LEFT JOIN
(
SELECT rownum, SUM(ClosingBalance) ClosingBalance
FROM WithClosingBalances
GROUP BY rownum
) c2 ON c1.rownum - c2.rownum = 1
)
SELECT
[StockNumber],
[InventoryName],
[Year],
[Month],
[Adj],
[iss],
[piss],
[Tsfr],
[return],
[rdj],
[rpo],
[xefr],
ClosingBalance,
OpeningBalance,
OpeningBalance + ClosingBalance AS CurrentMonthBalance
FROM WithOpeningBalances;
这将为您提供相同的输出。