Mysql
 sql >> Datenbank >  >> RDS >> Mysql

SQL Join derselben Tabelle basierend auf Zeitstempel und Bestandsebene

Das Übersetzen in SQL ist nicht so schwierig, aber die Leistung kann schlecht sein. Dadurch erhalten Sie den Zeitstempel, wann das Produkt wieder auf Lager war:

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

Bearbeiten:

Das Entfernen aufeinanderfolgender Zeilen mit Nullbestand ist komplizierter:

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 

Siehe Fiddle