-- SET @pbi_datetime = '2018-01-01 10:00:10'

-- POPULATE map_order_tax_rate
select @max_inserted_at:=coalesce(max(stg_inserted_at), FROM_UNIXTIME(1)) from map_order_tax_rate;
insert into `map_order_tax_rate`
(pk_map_order_tax_rate, fk_dim_tax_rate, order_id, `stg_inserted_at`, `inserted_at`)
  SELECT
    t.tax_id as pk_map_order_tax_rate,
    r.pk_dim_tax_rate as fk_dim_tax_rate,
    t.order_id as order_id,
    t.inserted_at as stg_inserted_at,
    @db_date_time as inserted_at
  FROM bim_stg_order_tax t
    join dim_tax_rate r
      on r.tax_rate_code = t.code
          and r.percent = t.percent/100
    left join map_order_tax_rate map
      on map.pk_map_order_tax_rate = t.tax_id
  WHERE t.inserted_at >= @max_inserted_at
    AND map.pk_map_order_tax_rate is NULL
order by stg_inserted_at;

-- {{IF_ANALYZE}}map_order_tax_rate{{/IF_ANALYZE}}
