, sum(sub.amount) as amount
, sum(greatest(least(sub.quantity, qoh.quantity - quantity_before), 0))
, sum(sub.amount*greatest(least(sub.quantity, qoh.quantity - quantity_before), 0)/sub.quantity)
- , `min(required_date)`
+ , min(`min(required_date)`)
, group_concat(distinct order_comment separator ';') as order_comment
, group_concat(distinct detail_comment separator ';') as detail_comment
FROM $sub sub