TABLE1:
ARTIKEL SUPPLIERID SALE_SUM_PIECES
TV SONY 7
TABLE2:
ROW_ID ARTIKEL SUPPLIERID PIECES
1 TV SONY 6
2 TV SONY 10
3 TV SONY 6
4 TV SONY 14
5 TV SONY 18
6 TV SONY 4
I need to subtract value X=23
on TABLE2."PIECES"
, only when the value TABLE1."SALE_SUM_PIECES" is less than the SUM of "PIECES" in TABLE2. For example: the value of TABLE1."SALE_SUM_PIECES"
is 7
. NOw I need to check at which row the value 7 goes less than
the SUM of TABLE2."PIECES"
.In the below example the first row in TABLE2 is not valid because 7 is greater than 6. But the second row in TABLE2 is valid since the SUM OF "PIECES" from row1 and row2 in TABLE2 i.e 6+10=16 is greater than 7. So, I need to subtract value of X=23
from the second row to the following rows in TABLE2
.
The query I have is as follows:
SELECT "SUPPLIERID", "ARTIKEL",
(case when ( cumulativesum - (select "SALE_SUM_PIECES" from T1 where T1."SUPPLIERID"=T2."SUPPLIERID" and T1."ARTIKEL" = T2."ARTIKEL" )) <= 0
then NULL
when ( cumulativesum - (select "SALE_SUM_PIECES" from TABLE1 T1 where T1."SUPPLIERID"=T2."SUPPLIERID" and T1."ARTIKEL" = T2."ARTIKEL" )) > 0
then
(case when @x - cumulativesum <= 0 and @x - (cumulativesum -PIECES) > 0
then 0
when @x - "cumulativesum" <= 0
then NULL
else @x - "cumulativesum"
end) as "VALUE_DRILL_DOWN"
from (SELECT T1."ARTIKEL", T1."SUPPLIERID", T1.PIECES
(select sum("PIECES")
from EXAMPLE_TABLE T2
where T2."ROW_ID" <= T1."ROW_ID" and T2."SUPPLIERID" = T1."SUPPLIERID" and T2."ARTIKEL"=T1."ARTIKEL"
) as "cumulativesum"
from EXAMPLE_TABLE T1
)
When I execute the above query I get the result as follows:
ROW_ID ARTIKEL SUPPLIERID PIECES VALUE_DRILL_DOWN
1 TV SONY 6 NULL
2 TV SONY 10 7
3 TV SONY 6 1
4 TV SONY 14 0
5 TV SONY 18 Null
6 TV SONY 4 Null
But I expect a result to be as follows:
ROW_ID ARTIKEL SUPPLIERID PIECES VALUE_DRILL_DOWN
1 TV SONY 6 NULL
2 TV SONY 10 13
3 TV SONY 6 7
4 TV SONY 14 0
5 TV SONY 18 Null
6 TV SONY 4 Null
I want the subtraction of ´X=23´ to start from the row in TABLE2 where the condition TABLE1."SALE_SUM_PIECES" < TABLE2."PIECES"
i.e from row2. Any suggestions?
Thanks in advance.