目的の出力を達成するには、製品売上の現在の合計を計算する必要があります。意味のあるデータを取得するには、salesのデータ テーブルは時系列で並べ替える必要があります。したがって、データを並べ替えるには、少なくとももう1つのフィールドが必要です。タイムスタンプであるか、idであるかは関係ありません。 分野。 idがあるとしましょう 販売テーブルのフィールド。これはあなたが説明したことを取得するためのクエリです:
SELECT
sales.id,
sales.store_id,
sales.product_id,
inventories.quantity-IFNULL(SUM(sales_2.quantity), 0) as inventory,
sales.quantity as sales,
inventories.quantity-IFNULL(SUM(sales_2.quantity), 0) - sales.quantity as remaining
FROM
sales
INNER JOIN
inventories ON inventories.store_id = sales.store_id
AND inventories.product_id = sales.product_id
LEFT JOIN
sales AS sales_2 ON sales_2.store_id = sales.store_id
AND sales_2.product_id = sales.product_id
AND sales_2.id < sales.id
GROUP BY sales.id , sales.store_id , sales.product_id
ORDER BY sales.id
salesの2番目のインスタンス sales_2というテーブル 以前の売上の合計を計算するために使用されます(sales_2.id<sales.id )
sales.idを除外できます selectから 句ですが、group byに保持する必要があります およびorder by 。