SQL查询 - 第一个值匹配求和结果

时间:2016-05-23 17:57:48

标签: mysql sql

我目前正在尝试根据和条件通过SQL查询获取特定值。

我的想法是,我需要特定的minimum_qty产品来减少交货时间。在示例中,值将是" 2"。我们的想法是查询总结了pop_supplied_qty列,直到它的> = minimum_qty。

查询结果应该是首次满足该条件的pop_order_num(653)。

当前查询如下所示:

CASE
    WHEN (sum(pop.pop_qty) - sum(pop.pop_supplied_qty)) >= minimum_qty
        THEN MIN(pop.pop_order_num)
    END AS pre_order_dt

表: enter image description here

感谢您的投入!

1 个答案:

答案 0 :(得分:0)

您可以使用内联变量和一些子查询来执行此操作:

  • 按产品订购记录,然后预订编号;
  • 添加累计和的值,当记录具有不同的产品引用时重置它,并在总和超过最小阈值时将布尔值设置为true;
  • 过滤累计数量已标记为已超过最低阈值的记录。

我假设minimum_qty存储在product表中:

select product_id,
       minimum_qty,
       pop_order_num,
       cumul_qty
from  (
      select @newqty := if(@p = product_id, @qty, 0) + qty,
             (@qty < minimum_qty and @newqty >= minimum_qty) filter,
             @p := product_id as product_id,
             minimum_qty,
             pop_order_num,
             @qty := @newqty as cumul_qty
      from  (
            select   pop.product_id,
                     pop.pop_order_num,
                     pop.pop_qty - pop.pop_supplied_qty as qty,
                     p.minimum_qty
            from     pre_order_dt pop
            inner join product p on p.product_id = pop.product_id 
            order by product_id,
                     pop_order_num
            limit    10000000000
            ) as base,
            (select @qty := 0) as init
      ) as extend
 where filter

SQL fiddle

请注意,limit子句只是一种预防措施,因为MySql引擎不必遵守order by,因为它出现在内部查询中。通过添加limit子句(应该指定一个非常高的值,因此它实际上不会遗漏任何记录),MySql将被强制应用order by,然后处理这个内部查询被包装的查询