MySQL从孤立的子查询中减去

时间:2011-11-21 19:59:15

标签: mysql join subquery

我有一个包含库存的表

ID   |   Product ID   |  In_Transit  |   Quantity   | Cumulative Quantity
=====+================+==============+==============+====================
1    |      1         |     0        |     1000     |      1000
2    |      1         |     0        |        1     |      1001
3    |      1         |     1        |       54     |      1055
4    |      1         |     1        |        1     |      1056

因此,产品ID 1的总库存为'1056'我使用SELECT MAX(ID)子查询连接与表格得到它,以获得其累计数量1056。

我想获得库存总额(减去运输中的所有金额)

所以1056 - 54 - 1 = 1001

我如何在一个查询中得到这个,所以我得到

Product ID | Total Inventory | Inventory on Hand (Excluding in Transit |
===========+=================+=========================================    
1          |     1056        |           1001

此外,我需要使用累积库存来获取总数而不是“SUM”,除了对传输中的那些进行求和,因为(那些不在传输中)具有大量记录,并且它们需要很长时间才能使用SUM。我可以用它来计算传输中的那些因为记录少得多

1 个答案:

答案 0 :(得分:4)

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)