In the SQL Server 2016 database, I have a table containing financial transactions:
CREATE TABLE Transactions
TxnId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
AccountId int NOT NULL,
DateTime datetime NOT NULL,
Amount money NOT NULL
)
I wrote VIEW
to display information about the current balance:
CREATE VIEW TransactionsWithBalance AS
SELECT
*,
SUM( Amount ) OVER ( PARTITION BY AccountId ORDER BY [DateTime], TxnId ) AS Balance
FROM
Transactions
When I request this view, the column Balance
contains all the values NULL
:
SELECT
*
FROM
TransactionsWithBalance
TxnId AccountId DateTime Amount Balance
1 1 2017-01-01 100.00 NULL
2 1 2017-01-02 200.00 NULL
3 2 2017-01-01 10.00 NULL
4 1 2017-01-03 300.00 NULL
But when I run the query (with the tag SUM( Amount ) OVER ( PARTITION BY... )
) directly in SSMS, I get the expected values in the column Balance
.
TxnId AccountId DateTime Amount Balance
1 1 2017-01-01 100.00 100.00
2 1 2017-01-02 200.00 300.00
3 2 2017-01-01 10.00 10.00
4 1 2017-01-03 300.00 600.00
Why does aggregation return values NULL
when querying internally VIEW
?
source
share