Mysql
 SQL >> Database >  >> RDS >> Mysql

Sottrarre una sottoquery isolata da una colonna MySQL

Un pattern chiaro è questo:

SELECT a.product_id,
       a.cumulative AS total_inventory,
       a.cumulative - COALESCE(b.quantity, 0) AS inventory_on_hand
FROM table1 a
JOIN (
  SELECT MAX(id) AS max_id
  FROM table1
  GROUP BY product_id
) m ON m.max_id = a.id
LEFT JOIN (
  SELECT product_id, SUM(quantity)
  FROM table1
  WHERE in_transit = 1
  GROUP BY product_id
) b ON a.product_id = b.product_id;

La prima sottoquery prende l’ultima riga per prodotto, la seconda somma le quantità in transito. COALESCE sostituisce eventuali NULL con zero.