Hello,
I have these tables (SQL Server 2019 Express):
Code:
CREATE TABLE tbl1Accounts (
AccountID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
AccountTypeID INT NOT NULL FOREIGN KEY REFERENCES tbl2AccountTypes (AccountTypeID),
CurrencyID INT NOT NULL FOREIGN KEY REFERENCES tbl1Currencies (CurrencyID),
AccountCode NVARCHAR(10) NOT NULL UNIQUE,
AccountName NVARCHAR(50) NOT NULL UNIQUE,
StartingBalance DECIMAL(10,2) NOT NULL,
IsHidden BIT NOT NULL DEFAULT 0,
DateAccountClosed DATE NULL,
CONSTRAINT CH_tbl1Accounts_DateAccountClosed CHECK (DateAccountClosed <= GETDATE()),
CONSTRAINT CH_tbl1Accounts_IsHidden_DateAccountClosed CHECK ((DateAccountClosed IS NOT NULL AND IsHidden = 1) OR (DateAccountClosed IS NULL))
)
CREATE TABLE tbl1Transactions (
TransactionID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
TransactionTypeID INT NOT NULL FOREIGN KEY REFERENCES tbl2TransactionTypes (TransactionTypeID),
PartnerID INT NULL FOREIGN KEY REFERENCES tbl1Partners (PartnerID),
AccountFromID INT NULL FOREIGN KEY REFERENCES tbl1Accounts (AccountID),
AccountToID INT NULL FOREIGN KEY REFERENCES tbl1Accounts (AccountID),
TransactionDate DATE NOT NULL,
AmountFrom DECIMAL(10,2) NULL,
AmountTo DECIMAL(10,2) NULL,
CZKRate DECIMAL(8,4) NULL,
TransactionDescription NVARCHAR(255) NULL,
Notes NVARCHAR(MAX) NULL,
CONSTRAINT CH_tbl1Transactions_TransactionTypeID CHECK ((TransactionTypeID = 1 AND AccountFromID IS NULL AND AccountToID IS NOT NULL AND AmountFrom IS NULL AND AmountTo IS NOT NULL) OR
(TransactionTypeID = 2 AND AccountFromID IS NOT NULL AND AccountToID IS NULL AND AmountFrom IS NOT NULL AND AmountTo IS NULL) OR
(TransactionTypeID = 3 AND AccountFromID IS NOT NULL AND AccountToID IS NOT NULL AND AmountFrom IS NOT NULL AND AmountTo IS NOT NULL)),
CONSTRAINT CH_tbl1Transactions_TransactionDate CHECK (TransactionDate <= GETDATE()),
CONSTRAINT CH_tbl1Transactions_CZKRate CHECK (CZKRate > 0)
)
I would like to get daily balances for each account (and display it as a line chart) based on SUMS of transactions associated with this account.
I could be summing all transactions until that respective day, but I fear that it wouldn't be very efficient, especially with many transactions.
Is there a correct way to do this? I assume that this is quite a basic request in data analytics.
Thank you in advance.
Tomas