mysql if inside select with aggregate functions

mysql if inside select with aggregate functions

我有一份清单 table,其中列出了多个地点的数量。我保留了一个数量值,现在我必须保留一个 "threshold" 值,当我达到阈值时停止销售产品。这只是一个软糖因素,所以当人们的库存不准确时,会有一点缓冲来确保他们不会过度承诺销售。

SELECT product, sum(quantity) as pooled, max(quantity) as maxincart FROM `inventory` WHERE location=1 OR location=2 OR location=3 GROUP by product

我尝试过的查询的主要问题是它们汇总了我所有的位置。在阈值之前这很好。现在我宁愿忽略的位置包含在我的总和中,我想要一个 IF 将它们从聚合函数中删除。

Sometimes it works fine. 
locationA has 7 and a threshold of 3.
locationB has 9 and a threshold of 4.

总结一下,就是 16 - 7 = 9 工作正常!

But then there are situations like this
locationA has 7 and a threshold of 3.
locationB has 0 and a threshold of 4. 

总和,7 - 7 = 0。LocationA 想卖掉他们的 4,但现在不能。

有没有办法在查询中嵌套 if,以便当一个位置的数量阈值 <=0 时,它将被排除在总和之外?我试图在 mysql 中进行操作以保持快速,找到了一些关于在 select 中使用的好信息,但是将它与分组依据和聚合函数结合起来让我卡住了。

我查询的table是中间的table,可以重组。因此,我愿意接受有关更改 table 以使其发挥作用的想法。我只是希望它快点,所以我不想在每个产品中进行另一个查询。我考虑过消除分组依据,按产品排序,将值存储在数组中,以及当产品通过数组更改 运行 时使用此逻辑......但这也意味着更大的循环和更多的内存使用.我希望 mysql 天才可以伸出援手。谢谢!

我发现很难理解这个问题,但我认为您的解决方案是按位置预先聚合(location/product?),然后再次聚合。像这样:

SELECT product,
       sum(greatest(quantity - threshhold, 0))
FROM (SELECT location, product, sum(quantity) as quantity, max(threshhold) as threshhold
      FROM `inventory`
      WHERE location IN (1, 2, 3) 
      GROUP by location, product
     ) lp
GROUP BY product;