查询以获取sqlite中的当前剩余库存

时间:2018-02-10 09:12:38

标签: sqlite

我有一个名为stock的表:

name   stock
------------
 a      100
 b      200
 c       50

sales

  name      sale
 --------------------
    a       30
    c       20
    d       30

结果应为:

name      stock
-----------------
   a       70
   b      200
   c       20
   d      -30

请告诉我sqlite查询。

我的查询:

select a.name, a.stock - b.sales as stock 
from stock as a 
inner join Sale as b on a.name = b.name

但是如何获得那些在库存中不存在但在销售中存在的名称?

1 个答案:

答案 0 :(得分:0)

我相信以下内容可以满足您的需求: -

SELECT name, sum(stock) - sum(sold) FROM
(
    SELECT name, sold, 0 as stock FROM sales
    UNION ALL
    SELECT name, 0 AS sold, stock FROM stock
)
GROUP BY name
ORDER BY name

基本上,内部SELECT提取一个表,每个组合有3列名称,已售出和库存,0表示缺失值。即: -

enter image description here

然后将其用作外部SELECT的来源,根据名称对销售和库存进行分组,并按照以下方式从库存中减去销售额: -

enter image description here