查询剩余余额

时间:2018-01-09 12:55:17

标签: sql sqlite

查询剩余余额

我正在使用SQLITE 3.1.1

场景是ff: 我们说总量是11。

enter image description here

公式应为:

总数量 - 使用的数量=剩余

它应该是这样的:

  • 首先:11 - 1 = 10
  • 第二名:10-6 = 4
  • 第三名:4 - 0 = 4 等等..

预期结果:

enter image description here

此外,剩余价值不能低于0.

我目前有这个SQL查询,但它没有得到下一个交易的剩余查询结果,而是始终以总数量开头。

SELECT
    filter_maintenance.maintenance_id,
    filter_maintenance.stock_id, 
    filter_maintenance.quantity_used,
    filter_maintenance.date_registered,
    filter_maintenance.date_changed,
    inventories.stock_name,
    SUM(inventories_order.order_quantity) - filter_maintenance.quantity_used AS Remaining
FROM filter_maintenance
INNER JOIN inventories ON filter_maintenance.stock_id = inventories.stock_id
INNER JOIN inventories_order ON filter_maintenance.stock_id = inventories_order.stock_id
GROUP BY filter_maintenance.maintenance_id

这是我目前的输出:

enter image description here

非常感谢您的帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

由于您使用的是sqllite并且没有窗口函数,因此您需要使用自联接。我认为maintenance_idfilter_maintenance中的主键。

SELECT
    filter_maintenance.maintenance_id,
    filter_maintenance.stock_id, 
    filter_maintenance.quantity_used,
    filter_maintenance.date_registered,
    filter_maintenance.date_changed,
    inventories.stock_name,
    sum(inventories_order.order_quantity) - filter_maintenance.sum_quantity_used AS Remaining
FROM 
(
    SELECT  fm1.*,
            sum(fm2.quantity_used) AS sum_quantity_used 
    FROM filter_maintenance fm1
    INNER JOIN filter_maintenance fm2 ON fm1.stock_id = fm2.stock_id and
                                         fm1.date_registered >= fm2.date_registered
    GROUP BY fm1.maintenance_id
) filter_maintenance
INNER JOIN inventories ON filter_maintenance.stock_id = inventories.stock_id
INNER JOIN inventories_order ON filter_maintenance.stock_id = inventories_order.stock_id
GROUP BY filter_maintenance.maintenance_id