Click to See Complete Forum and Search --> : SQL - calculate result


arga
01-12-2009, 06:57 AM
Please, help me with a SELECT instruction (UNION, JOIN, maybe, I.m not sure) in order to display values extracted from two tables, as follows:

CODE ; ID ; SUMV ; RESULT; DATE
A ; 1 ; 100 ; 4900 ; 01.jan.2009
A ; 2 ; 200 ; 4700 ; 05.jan.2009
A ; 3 ; 500 ; 4200 ; 10.jan.2009
B ; 4 ; 1000 ; 6000 ; 02.jan.2009
B ; 5 ; 1500 ; 4500 ; 04.jan.2009

- table 1 contains:
CODE ; VALUE (start value)
A ; 5000
B ; 7000

- table 2 contains:
CODE ; ID; SUMV; DATE
A ; 1 ; 100 ; 01.jan.2009
A ; 2 ; 200 ; 05.jan.2009
A ; 3 ; 500 ; 10.jan.2009
B ; 4 ; 1000 ; 02.jan.2009
B ; 5 ; 1500 ; 04.jan.2009

- the calculated RESULT is:
1 ; (5000 - 100) = 4900
2 ; (5000 - 100 - 200) = 4700
3 ; (5000 - 100 - 200 - 500) = 4200
4 ; (7000 - 1000) = 6000
5 ; (7000 - 1000 - 1500) = 4500

I do not know how to obtain for each displayed line the above calculated RESULT - I mean I know is RESULT = VALUE - sum(SUMV) but I do not know the WHERE condition.

And as if it was not enough the mentioned problem, complications occur ::confused:
- if other records are to be done, ex.: code = A, id = 6, sumv = 250 and date = 03.jan.2009, record which must be inserted between 01.jan.2009 and 05.jan.2009, the result has to be recalculated:

CODE; ID ; SUMV ; RESULT; DATE
A ; 1 ; 100 ; 4900 ; 01.jan.2009
A ; 6 ; 250 ; 4650 ; 03.jan.2009
A ; 2 ; 200 ; 4450 ; 05.jan.2009
A ; 3 ; 500 ; 3950 ; 10.jan.2009
B ; 4 ; 1000 ; 6000 ; 02.jan.2009
B ; 5 ; 1500 ; 4500 ; 04.jan.2009

Thank you !

Mindzai
01-12-2009, 09:53 AM
Untested:

SELECT
table1.CODE,
table1.ID,
table2.SUMV,
(table1.VALUE - table2.SUMV) AS RESULT,
table2.DATE
FROM table2
INNER JOIN table1 ON table1.CODE = table2.CODE
WHERE table2.ID = 1
LIMIT 1

arga
01-13-2009, 02:28 AM
I solved the problem using next code:

select t2.code, t2.id,
t1.val - sum(sumv) over (partition by t2.code order by t2.id) sumv,
t2.thedate
from table_2 t2, table_1 t1
where t2.code = t1.code
order by t1.code, t2.thedate

Thank you !