INSERT INTO item_price ( item_id, price, store_id )
SELECT id, iif(cdbl(price) < cdbl(bminprice), bminprice, price), 1
FROM [SELECT id, round(iif(calc_price < bCost * (1 + STORE_min_markup), bCost * (1 + STORE_min_markup), Iif(calc_price > bCost * (1 + STORE_max_markup),bCost * (1 + STORE_max_markup),calc_price)),1)-0.06 AS price, bminprice
FROM (SELECT ID, ps.STORE_min_markup, ps.STORE_max_markup, Iif(store_qty > 0,ps.STORE_min_order_profit_instock,ps.STORE_min_order_profit) as min_order_profit, iif(bCost <= (select STORE_cost_threshold from hub_price_settings where store_id = 1),STORE_min_qty_under_cost_threshold,Nz(baipo,9)) as items_per_order,
bCost+(min_order_profit/(Nz(items_per_order,2)+.01)) AS calc_price, bCost, bminprice
FROM
hub_price_settings ps
inner join (select i.ID, Min(Nz(sf.Cost, xf.cost_per_bottle + Nz(xf.split_case_charge,0))) as bcost, Max(iif(Nz(xf.min_price,0)=0,Nz(sf.min_price,0),Nz(xf.min_price,0))) as bminprice, Max(sf.manual_price) as bmanual_price, Max(Nz(sf.qty,0) + Nz(xf.qty_avail,0)) as btqty, Sum(sf.qty) as store_qty, Avg(pa.aipo) as baipo, 1 as store_id
from (((item i
left join item_store2 si on (i.ID = si.item_id and si.store_id = 1))
left join STORE_store_feed sf on (si.store_sku = sf.sku and sf.qty > 0))
left join item_xref xf on (i.ID = xf.item_id and xf.store_id = 1))
left join pricing_aipo pa on i.id = pa.item_id
where Nz(sf.Cost, xf.cost_per_bottle + Nz(xf.split_case_charge,0)) > 0 and Nz(sf.qty,0) + Nz(xf.qty_avail,0) > 0
group by i.ID
) b on b.store_id = ps.store_id
) AS x
]. AS z;