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

-- POPULATE map_salesrule
select @max_inserted_at:=coalesce(max(stg_inserted_at), FROM_UNIXTIME(1)) from map_salesrule;
insert into `map_salesrule`
(fk_dim_salesrule, order_item_id, `stg_inserted_at`, `inserted_at`)
  select
    ifnull(dim.pk_dim_salesrule, -1) as fk_dim_salesrule,
    r.order_item_id as order_item_id,
    r.inserted_at as stg_inserted_at,
    @db_date_time as inserted_at
  from bim_stg_order_item_rule r
  left join dim_salesrule dim
      on dim.rule_id = r.applied_rule_id
  left join map_salesrule m
      on m.fk_dim_salesrule = ifnull(dim.pk_dim_salesrule, -1)
      and m.order_item_id = r.order_item_id
  where r.inserted_at >= @max_inserted_at
    AND m.fk_dim_salesrule is NULL
order by stg_inserted_at;


-- {{IF_ANALYZE}}map_salesrule{{/IF_ANALYZE}}
