
UPDATE product_cost_price__history SET write_date=create_date WHERE write_date IS NULL;

INSERT INTO product_average_cost (cost_price, product, effective_date, create_uid, create_date)
  SELECT cost_price, product, write_date::DATE, create_uid, write_date
  FROM product_cost_price__history AS ch
  WHERE cost_price IS NOT NULL AND product IN (select id from product_product)
  ORDER BY ch.write_date ASC;
