Guys i have this problem on subtracting the the two tables (Deliveries
and Returns
) by its TOTAL_QUANTITY
grouped by their CONTAINER_TYPE
and CUSTOMER_NAME
, this sample query returns the column Customer_Balance
of 0
if I subtracted for example 5 - 0
, but if i subtracted 5 -1
it returns 4
.
select TOTAL_DELIVERY.CUSTOMER_NAME,
TOTAL_DELIVERY.CONTAINER_TYPE,
coalesce(TOTAL_DELIVERY.TOTAL_QUANTITY, 0) as TOTAL_DELIVERY,
coalesce(TOTAL_PULLOUT.TOTAL_QUANTITY, 0) as TOTAL_PULLOUT,
coalesce((TOTAL_DELIVERY.TOTAL_QUANTITY - TOTAL_PULLOUT.TOTAL_QUANTITY), 0) as CUSTOMER_BALANCE
from TOTAL_DELIVERY
left join TOTAL_PULLOUT
on TOTAL_DELIVERY.CUSTOMER_NAME = TOTAL_PULLOUT.CUSTOMER_NAME
and TOTAL_DELIVERY.CONTAINER_TYPE = TOTAL_PULLOUT.CONTAINER_TYPE
Deliveries Table (View)
================
----------------------------------------------
CUSTOMER_NAME| CONTAINER_TYPE | TOTAL_QUANTITY
-------------+----------------+---------------
Bryan | Slim | 5
-------------+----------------+---------------
Bryan | Jug | 5
-------------+----------------+---------------
Returns Table (View)
=============
CUSTOMER_NAME| CONTAINER_TYPE| TOTAL_QUANTITY
-------------+---------------+---------------
Bryan | Slim | 5
-------------+---------------+---------------
Expected output
===============
Customer | Container | Total_Delivery | Total_Return | Customer_Balance |
---------+-----------+----------------+--------------+------------------
Bryan | Slim | 5 | 5 | 0 |
---------+-----------+----------------+--------------+------------------
Bryan | Jug | 5 | 0 | 5 |
---------+-----------+----------------+---------------------------------
My INCORRECT Result output (incorrect result at the bottom right cell)
=========
Customer | Container | Total_Delivery | Total_Return | Customer_Balance |
---------+-----------+----------------+--------------+------------------
Bryan | Slim | 5 | 5 | 0 |
---------+-----------+----------------+--------------+------------------
Bryan | Jug | 5 | 0 | 0 |
---------+-----------+----------------+---------------------------------
can you please tell me what am i doing wrong? thank you!
(TOTAL_DELIVERY.TOTAL_QUANTITY - TOTAL_PULLOUT.TOTAL_QUANTITY)
must be
(coalesce(TOTAL_DELIVERY.TOTAL_QUANTITY,0) - coalesce(TOTAL_PULLOUT.TOTAL_QUANTITY, 0))