Mysql
 sql >> Base de données >  >> RDS >> Mysql

MySQL soustrait d'une sous-requête isolée

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)