-- ds_sa_idx 가 NULL 인 지정판매소에 구·군(bo_gugun_code)별 최다 발주 대행소를 매핑
-- mysql --default-character-set=utf8mb4 -u ... -p DBNAME < writable/database/designated_shop_ds_sa_idx_backfill.sql

SET NAMES utf8mb4;

UPDATE `designated_shop` ds
INNER JOIN (
  SELECT bo.bo_lg_idx, bo.bo_gugun_code, bo.bo_agency_idx
  FROM `bag_order` bo
  INNER JOIN (
    SELECT bo_lg_idx, bo_gugun_code, bo_agency_idx, COUNT(*) AS cnt,
      ROW_NUMBER() OVER (
        PARTITION BY bo_lg_idx, bo_gugun_code
        ORDER BY COUNT(*) DESC, bo_agency_idx DESC
      ) AS rn
    FROM `bag_order`
    WHERE bo_status = 'normal'
      AND bo_agency_idx IS NOT NULL
      AND TRIM(bo_gugun_code) != ''
    GROUP BY bo_lg_idx, bo_gugun_code, bo_agency_idx
  ) ranked ON ranked.bo_lg_idx = bo.bo_lg_idx
    AND ranked.bo_gugun_code = bo.bo_gugun_code
    AND ranked.bo_agency_idx = bo.bo_agency_idx
    AND ranked.rn = 1
  WHERE bo.bo_status = 'normal'
  GROUP BY bo.bo_lg_idx, bo.bo_gugun_code, bo.bo_agency_idx
) map ON map.bo_lg_idx = ds.ds_lg_idx AND map.bo_gugun_code = ds.ds_gugun_code
SET ds.ds_sa_idx = map.bo_agency_idx
WHERE ds.ds_sa_idx IS NULL;
