CREATE TEMPORARY TABLE tmp_invite_campaign_monthly_progress_merge AS
SELECT
  MIN(id) AS id,
  sys_origin,
  inviter_user_id,
  LEFT(month_key, 6) AS month_key,
  SUM(invite_count) AS invite_count,
  SUM(valid_user_count) AS valid_user_count,
  SUM(total_recharge_coins) AS total_recharge_coins,
  SUM(reward_gold_coins) AS reward_gold_coins,
  MIN(create_time) AS create_time,
  MAX(update_time) AS update_time
FROM invite_campaign_monthly_progress
WHERE CHAR_LENGTH(month_key) = 8
GROUP BY sys_origin, inviter_user_id, LEFT(month_key, 6);

DELETE FROM invite_campaign_monthly_progress
WHERE CHAR_LENGTH(month_key) = 8;

INSERT INTO invite_campaign_monthly_progress (
  id,
  sys_origin,
  inviter_user_id,
  month_key,
  invite_count,
  valid_user_count,
  total_recharge_coins,
  reward_gold_coins,
  create_time,
  update_time
)
SELECT
  id,
  sys_origin,
  inviter_user_id,
  month_key,
  invite_count,
  valid_user_count,
  total_recharge_coins,
  reward_gold_coins,
  create_time,
  update_time
FROM tmp_invite_campaign_monthly_progress_merge
ON DUPLICATE KEY UPDATE
  invite_count = invite_campaign_monthly_progress.invite_count + VALUES(invite_count),
  valid_user_count = invite_campaign_monthly_progress.valid_user_count + VALUES(valid_user_count),
  total_recharge_coins = invite_campaign_monthly_progress.total_recharge_coins + VALUES(total_recharge_coins),
  reward_gold_coins = invite_campaign_monthly_progress.reward_gold_coins + VALUES(reward_gold_coins),
  update_time = GREATEST(invite_campaign_monthly_progress.update_time, VALUES(update_time));

DROP TEMPORARY TABLE tmp_invite_campaign_monthly_progress_merge;

CREATE TEMPORARY TABLE tmp_invite_campaign_task_claim_merge AS
SELECT
  MIN(id) AS id,
  sys_origin,
  inviter_user_id,
  LEFT(month_key, 6) AS month_key,
  rule_id,
  MIN(claim_time) AS claim_time,
  MIN(create_time) AS create_time,
  MAX(update_time) AS update_time
FROM invite_campaign_task_claim
WHERE CHAR_LENGTH(month_key) = 8
GROUP BY sys_origin, inviter_user_id, LEFT(month_key, 6), rule_id;

DELETE FROM invite_campaign_task_claim
WHERE CHAR_LENGTH(month_key) = 8;

INSERT INTO invite_campaign_task_claim (
  id,
  sys_origin,
  inviter_user_id,
  month_key,
  rule_id,
  claim_time,
  create_time,
  update_time
)
SELECT
  id,
  sys_origin,
  inviter_user_id,
  month_key,
  rule_id,
  claim_time,
  create_time,
  update_time
FROM tmp_invite_campaign_task_claim_merge
ON DUPLICATE KEY UPDATE
  claim_time = LEAST(invite_campaign_task_claim.claim_time, VALUES(claim_time)),
  update_time = GREATEST(invite_campaign_task_claim.update_time, VALUES(update_time));

DROP TEMPORARY TABLE tmp_invite_campaign_task_claim_merge;
