SQL计算来自两个不同表的计数之间的比率

时间:2019-06-26 14:25:22

标签: mysql sql

我有三个表: 具有列ID,说明的产品
带列ID,分支的需求
具有列ID,分支的库存

我想计算每个产品和分支的比率,并得到类似的结果

product branch demands stock ratio
shoes   A      4       8     2
shoes   B      8       4     0.5
shirts  A      1       1     1

我认为这很容易,但是此后我被卡住了

SELECT products.id, products.description,demands.branch, COUNT(demands.branch)
FROM products
LEFT JOIN demands ON (demands.id=products.id)
WHERE demands.id IS NOT NULL
GROUP BY products.id, demands.branch

在没有库存的情况下可能会有需求,而我正在使用嵌入在管理系统中的mySQL数据库

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则一种方法使用union all

select id, branch, sum(demand), sum(stock), sum(stock) / nullif(sum(demand), 0) as ratio
from ((select id, branch, 1 as demand, 0 as stock
       from demands
      ) union all
      (select id, branch, 0 as demand, 1 as stock
       from stock
      )
     ) ds
group by id, branch;