I only want to sum the applied amount when a ledger amount in another table is positive
Example
Table A
Statement # ID
500 1
500 2
500 3
500 4
Table B
Ledger_Amount Type ID
-389.41 Credit 1
-1218.9 Credit 2
-243.63 Credit 3
3485.19 Invoice 4
Table C
Applied_Amount ID
389.41 1
1218.9 2
243.63 3
1633.25 4
The current code is
(sum(applied_amount) over (partition by statement_number),0)
It is coming up with a total of $3485.19 because it is summing by statement number only, and all IDs have the same statement number, the value I want it to come up with is $1633.25 because it should not sum anything where the ledger_amount in table B is less than 0, so ID 1,2,3 should not be summed only valid value is ID 4
1条答案
按热度按时间bq3bfh9z1#
There is one approach:
Assuming ID is a unique column, first we should get the IDs we'd work on based on the statementnumber and save them in a temp table:
Then, eliminate the IDs where they have a negative number in table B
Finally, use the ids left to get your sum: