我目前正在尝试根据和条件通过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
感谢您的投入!
答案 0 :(得分:0)
您可以使用内联变量和一些子查询来执行此操作:
我假设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
请注意,limit
子句只是一种预防措施,因为MySql引擎不必遵守order by
,因为它出现在内部查询中。通过添加limit
子句(应该指定一个非常高的值,因此它实际上不会遗漏任何记录),MySql将被强制应用order by
,然后处理这个内部查询被包装的查询