-- 取登陆最早时间 逻辑:如果之前没出现过,那插入这条记录做最早用户登陆时间
-- 首次写入数据sql

INSERT INTO dim.first_user(game_channel_id,game_identity,game_platform_id,relation_id,prodid,user_id,ds,ds_date)
WITH active_account_tmp AS (
  SELECT distinct
    t1.channel_id,
    t1.game_identity,
    t1.platform_id,
    t1.user_id,
    '${bizdate}' AS ds  -- 直接赋值替代min(ds)
  FROM ods.active_account_list t1
  WHERE t1.ds = '${bizdate}'
    AND NOT EXISTS (
      SELECT 1
      FROM dim.first_user t3
      WHERE t1.channel_id = t3.game_channel_id
        AND t1.game_identity = t3.game_identity
        AND t1.platform_id = t3.game_platform_id
        AND t1.user_id = t3.user_id
    )
)
SELECT t2.game_channel_id
        ,t2.game_identity
        ,t2.game_platform_id
        ,t2.relation_id
        ,t2.product_id prodid
        ,t1.user_id
        ,t1.ds ds
        ,'${biz-date}' ds_date
FROM    active_account_tmp t1
inner join
dim.game_product_relation t2
ON      t1.channel_id = t2.game_channel_id
AND     t1.game_identity = t2.game_identity
AND     t1.platform_id = t2.game_platform_id

ON CONFLICT (relation_id,user_id)
DO UPDATE SET game_channel_id = EXCLUDED.game_channel_id,game_identity = EXCLUDED.game_identity ,game_platform_id = EXCLUDED.game_platform_id
,prodid = EXCLUDED.prodid,user_id = EXCLUDED.user_id,ds = EXCLUDED.ds,ds_date = EXCLUDED.ds_date
;