I think this will work, although it would be nice to have sample data to verify:
SELECT COALESCE(SUM(a.samt), 0) - COALESCE(SUM(b.samt), 0)
+ COALESCE(SUM(CASE WHEN ord.stat = 16
AND b.samt < 0
THEN ord.samt END), 0)
FROM PUB.ord ord
LEFT JOIN PUB.opn a
ON a.subsnum = ord.subsnum
AND a.onum = ord.onum
AND a.samt >= 0
AND ord.stat != 16
LEFT JOIN PUB.opn b
ON b.subsnum = ord.subsnum
AND b.onum = ord.onum
AND b.samt < 0
AND ord.stat = 16
WHERE ord.DM1 IN('XCWAJC25', 'WCWAMO73')
AND ord.prdcde = 'CSC'
GROUP BY ord.DM1
Notes on query/stuff:
- Always explicitly qualify joins, don't use the comma-separated
FROM
clause - I don't think you needed
ord.DM1 != ''
, given that values have to be in a specific set - Putting a clause into a
LEFT JOIN
condition instead of theWHERE
clause has a slightly different effect; it adds the condition to the join, instead of the filtering. This means that rows can be excluded based on something in the left table, regardless of whether you need the actual row (this is whyord.stat
ended up in theLEFT JOIN
s).INNER JOIN
s would technically behave the same way, but it isn't usually noticeable because causing the right table to be excluded also excludes the left table.