Post by mcnewsxpI have a table that has an Income and Expense columns. I have added a
Balance column. I want to update the Balance column with result of
Income - Expense. The tricky part is that the Balance column must
accumulate using either AccountingEntryID column order or the EntryDate
column order. the example data I included is pretty strait forward.
CREATE TABLE [dbo].[AccountEntry](
[AccountEntryID] [int] IDENTITY(1,1) NOT NULL,
[Income] [money] NULL,
[Expense] [money] NULL,
[EntryDate] [datetime] NULL,
[Balance] [money] NULL
) ON [PRIMARY]
GO
UPDATE AccountEntry
SET Balance = (SELECT SUM(b.Income - b.Expense)
FROM AccountEntry b
WHERE b.AcountEntryID <= a.AccountEntryID)
FROM AccountEntry b
You will need to figure out what applies if any of Income and Expense are
NULL.
And, yeah, I ignored EntryDate. Supposedly transactions are entered in
order, so AccountEntry should be all you need. On top of that EntryDate
is nullable - how would those rows be handled. Yes, you can get EntryDate
in there:
UPDATE AccountEntry
SET Balance = (SELECT SUM(b.Income - b.Expense)
FROM AccountEntry b
WHERE (b.EntryDate <= a.EntryDate OR
b.EntryDate = a.EntryDate AND
b.AcountEntryID <= a.AccountEntryID))
FROM AccountEntry b
But performance will be horrendeous, and you will lose the rows with
NULL in them.
--
Erland Sommarskog, SQL Server MVP, ***@sommarskog.se
Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx