-- 汇总游戏数据


INSERT INTO ads.game_data(relation_id,prodid,ds,ds_type,ds_name,active_user_cut,play_user_cut,order_amount,new_active_user_cut,
                          new_play_user_cut,new_order_amount)

SELECT
    relation_id,
    prodid,
    ds,
    ds_type,
    ds_name,
    active_user_cut,
    play_user_cut,
    order_amount,
    new_active_user_cut,
    new_play_user_cut,
    new_order_amount
FROM (
    SELECT t1.relation_id,
           t1.product_id AS prodid,
           t.ds,
           'd' AS ds_type,
           '天' AS ds_name,
           SUM(CASE WHEN t.type = 'hyzh' THEN active_user_cut ELSE 0 END) AS active_user_cut,
           SUM(CASE WHEN t.type = 'hyzh' THEN play_user_cut ELSE 0 END) AS play_user_cut,
           SUM(CASE WHEN t.type = 'hyzh' THEN order_amount ELSE 0 END) AS order_amount,
           SUM(CASE WHEN t.type = 'xzh' THEN active_user_cut ELSE 0 END) AS new_active_user_cut,
           SUM(CASE WHEN t.type = 'xzh' THEN play_user_cut ELSE 0 END) AS new_play_user_cut,
           SUM(CASE WHEN t.type = 'xzh' THEN order_amount ELSE 0 END) AS new_order_amount
    FROM dws.game_user_data t
    INNER JOIN dim.game_product_relation t1 ON
        t.game_channel_id = t1.game_channel_id AND
        t.game_identity = t1.game_identity AND
        t.game_platform_id = t1.game_platform_id
    where t.ds<='${bizdate}'
    GROUP BY t1.relation_id, t1.product_id, t.ds

    UNION ALL

    SELECT t1.relation_id,
           t1.product_id AS prodid,
           t.ds,
           'm' AS ds_type,
           '月' AS ds_name,
           SUM(CASE WHEN t.type = 'hyzh' THEN active_user_cut ELSE 0 END) AS active_user_cut,
           SUM(CASE WHEN t.type = 'hyzh' THEN play_user_cut ELSE 0 END) AS play_user_cut,
           SUM(CASE WHEN t.type = 'hyzh' THEN order_amount ELSE 0 END) AS order_amount,
           SUM(CASE WHEN t.type = 'xzh' THEN active_user_cut ELSE 0 END) AS new_active_user_cut,
           SUM(CASE WHEN t.type = 'xzh' THEN play_user_cut ELSE 0 END) AS new_play_user_cut,
           SUM(CASE WHEN t.type = 'xzh' THEN order_amount ELSE 0 END) AS new_order_amount
    FROM dws.game_user_data_month t
    INNER JOIN dim.game_product_relation t1 ON
        t.game_channel_id = t1.game_channel_id AND
        t.game_identity = t1.game_identity AND
        t.game_platform_id = t1.game_platform_id
    GROUP BY t1.relation_id, t1.product_id, t.ds
) tt

ON CONFLICT (relation_id,ds,ds_type) DO UPDATE SET prodid=EXCLUDED.prodid,ds_name = EXCLUDED.ds_name, active_user_cut = EXCLUDED.active_user_cut ,play_user_cut = EXCLUDED.play_user_cut
    ,order_amount = EXCLUDED.order_amount,new_active_user_cut = EXCLUDED.new_active_user_cut,new_play_user_cut = EXCLUDED.new_play_user_cut,new_order_amount = EXCLUDED.new_order_amount
;