try it
SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM
(SELECT product_id, sum(quantity) as inventory_total
FROM inventory
GROUP BY product_id) inv_t LEFT OUTER JOIN
(SELECT product_id, count(*) AS sales_total
FROM sales
GROUP BY product_id) sale_t
ON (inv_t.product_id = sale_t.product_id)
This is a better solution than several other published ones that do not take into account the fact that some products may not have corresponding rows in the sales table. You want to make sure that such products also appear in the results.
NVL is an Oracle-specific function that returns the value of the first argument if it is not null, in which case it returns the value of the second argument. All commercial DBMSs have equivalent functions - you can use CASE in MySQL with the same effect.
source
share