database - Sum balance via Price + Balance From previous row -


i have oracle database 11g table 'transaction' . want balance.

i have now:

|   date   |   description    | min_plus | amount | balance | | 4-7-2015 | gift dad    | +        | 45,00  |       0 | | 5-7-2015 | gift sister   | -        | 3,00   |       0 | | 6-7-2015 | gift aunt   | +        | 2,50   |       0 | 

i'm looking for:

|   date   |   description    | min_plus | amount | balance | | 4-7-2015 | gift dad    | +        | 45,00  |  45,00  | | 5-7-2015 | gift sister   | -        | 3,00   |  42,00  | | 6-7-2015 | gift aunt   | +        | 2,50   |  44,50  | 

is possible virtual colmn, better use pl/sql or not possible do?

you can running total in plain sql, when select data display. no need create balance column or pl/sql trick. oracle windowing functions nifty use! in case, want sum() amount column first row current row in order of transaction date. can express in surprisingly plain language:

with sample_data (     select to_date('04-07-2015', 'mm-dd-yyyy') datecol, 'gift dad' description, '+' min_plus, 45 amount dual union     select to_date('05-07-2015', 'mm-dd-yyyy'), 'gift sister', '-', 3 dual union     select to_date('06-07-2015', 'mm-dd-yyyy'), 'gift aunt', '+', 2 dual)  select datecol, description, min_plus, amount, sum(case when min_plus = '-' -1 * amount else amount end)    on (order datecol rows between unbounded preceding , current row) balance sample_data order datecol; 

sql fiddle example

a few notes: window function sum() on (partition ... order ... range) magic. in case not partitioning (restarting calculation) data set, can skip that. including order by in window ensure summing values in correct order, expressing order by entire value set normal. , can google range clause, can see it's rather plain language.

by way, using char transaction sign awkward. suggest storing signed integer, 1 , -1, can multiply amount transaction sign column.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -