So I have the below code
SELECT PICK_SO_NUMBER, CUSTOMER, SO_PRODUCT, DO_QUANTITY, DO_PACKING, DO_DATE,
COALESCE(INVOICED_QTY, 0) AS INVOICED_QTY,
DO_QUANTITY-INVOICED_QTY AS NOT_INVOICED,
INVOICE_PACKING
FROM VW_TRAFFIC_PO_SIDE
WHERE DO_QUANTITY > INVOICED_QTY OR (INVOICED_QTY IS NULL AND DO_QUANTITY IS NOT NULL)
The line below the coalesce, is suppose to subtract the DO_QUANTITY from INVOICED_QTY, however when INVOICED_QTY is NULL, it no longer subtracts by 0, it subtracts by null, and thus the new column returns nulls where INVOICED_QTY is null
I tried multiple things: tried coalesce to a case, writing the coalesce as INVOICED and then using INVOICED in the subtraction expression, I tried using the coalesce in the same line as the subtraction (without comma in between, I felt this was the solution that would work best, but couldn’t get it to compile)
It gets confusing when you use the same alias ‘invoiced_qty’ in the select-list and in the WHERE clause. The value in the subtraction is the raw column value, not the coalesced value from the previous select-list item. The same is true in the WHERE clause.