In a 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 a VIEW to display running balance information:
CREATE VIEW TransactionsWithBalance AS
SELECT
*,
SUM( Amount ) OVER ( PARTITION BY AccountId ORDER BY [DateTime], TxnId ) AS Balance
FROM
Transactions
When I query this view, the Balance column contains all NULL values:
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 SUM( Amount ) OVER ( PARTITION BY... )) query directly in SSMS I get the expected values in the Balance column.
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 is the aggregate returning NULL values when queried inside a VIEW?