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

SQL Joindre la même table en fonction de l'horodatage et du niveau d'inventaire

Traduire en SQL n'est pas si difficile, mais les performances peuvent être mauvaises. Cela vous donnera l'horodatage du retour en stock du produit :

SELECT inv.*,
 ( SELECT MIN(`inv2`.`in_stock_at`)
   FROM inventories AS inv2
   WHERE inv2.`product_id` = inv.`product_id`   -- same product
     AND inv2.`pusher_id` = `inv`.`pusher_id`   -- same pusher
     AND `inv2`.`created_at` > inv.`created_at` -- later timestamp
     AND `inv2`.`item_count` > 0                -- in stock
 ) AS inStockAgain_at
from `inventories` AS inv
WHERE inv.`item_count` <= 0   -- out of stock
 -- AND inv.`product_id`=9

Modifier :

Supprimer des lignes consécutives sans stock est plus compliqué :

SELECT inv.*, dt.inStockAgain_at
FROM inventories AS inv
JOIN
 ( 
   SELECT product_id, pusher_id, 
      MIN(created_at) AS min_created_at,
     inStockAgain_at
   FROM
    (
      SELECT product_id, pusher_id, created_at,
       ( SELECT MIN(inv2.created_at)
         FROM inventories AS inv2
         WHERE inv2.product_id = inv.product_id -- same product
           AND inv2.pusher_id = inv.pusher_id   -- same pusher
           AND inv2.created_at > inv.created_at -- later timestamp
           AND inv2.item_count > 0              -- in stock
       ) AS inStockAgain_at
      FROM inventories AS inv
      WHERE inv.item_count <= 0  
    ) AS dt
   GROUP BY product_id, pusher_id, inStockAgain_at
 ) AS dt
ON inv.product_id = dt.product_id
AND inv.pusher_id = dt.pusher_id 
AND inv.created_at = dt.min_created_at 

Voir violon