Stock
Product Quantity Unit
-------------------------------
001 5 box
001 10 bottle
001 60 gallon
Conversion
Unit1 Unit2 Rate
----------------------
box bottle 20
bottle gallon 30
Unit1 = Unit2 * Rate
如何编写 SQL 查询来计算特定单位(例如示例中的瓶子)的 sum(quantity)?
select product, sum(quantity * ....) from Stock group by product
getRate(unit1, unit2) 之类的数据库函数可以完成这项工作吗?性能如何?
最佳答案
您需要扩展转换表,使其包含所有组合。这是一次性的工作,但您需要像这样添加行:
Unit1 Unit2 Rate
----------------------
box bottle 20
bottle gallon 30
gallon bottle 1/30
然后你可以使用LEFT JOIN
:
SELECT s.product, SUM(s.quantity * coalesce(c.rate, 1))
FROM stock s LEFT JOIN
conversion c
ON s.unit = c.unit1 AND c.unit2 = 'bottle'
GROUP BY s.product
关于mysql - 带数量单位转换的group-by查询sql怎么写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55505746/