您可以通过在线变量和一些子查询做到这一点:
- 为了通过产品的记录,然后预购数量;
- 为累计总和添加值,当记录具有不同的产品参考时将其重置,并在总和超过最小阈值时将布尔值设置为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
。
Did this answer your题? – trincot
你能告诉我这是否对你有用吗? – trincot