MySQL subtract from isolated subquery

流过昼夜 提交于 2019-12-11 15:23:59

问题


I have a table containing inventory

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

So the total inventory for product id 1 is '1056' I get this using a SELECT MAX(ID) subquery join with the table to get its cumulative quantity which is 1056.

I would like to get the Inventory total (subtracting all the amounts in transit)

So 1056 - 54 - 1 = 1001

How would I get this in one query so i get

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

Also i need to use the cumulative inventory to get the total as opposed to 'SUM', except for summing those in transit because (those not in transit) have a large number of records and they take ages to SUM. I can use it to sum those in transit because there are far fewer records


回答1:


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)


来源:https://stackoverflow.com/questions/8217756/mysql-subtract-from-isolated-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!