我目前正在尝试通过一个基于sum条件的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
表:
感谢您的投入!
发布于 2016-05-23 19:23:17
您可以使用内联变量和一些子查询来执行此操作:
我假设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
。
https://stackoverflow.com/questions/37397529
复制相似问题