-- Databricks notebook source
-- drop table if exists dm.DM_TD_EXTERNAL_BRAND_MARKET;
-- create table if not exists dm.DM_TD_EXTERNAL_BRAND_MARKET
-- using parquet as
INSERT OVERWRITE dm.DM_TD_EXTERNAL_BRAND_MARKET (
  TA_NAME,
  RNK,
  BRAND_CODE,
  BRAND_NAME,
  KEYCOMPATITORCN,
  KEYCOMPATITOREN,
  CLASS,
  IMSBRAND,
  CORP,
  MARKET,
  MARKETDESC,
  DEFAULTFLAG,
  VBP,
  VBPFLAG,
  VALUETYPE,
  Strategicbrand,
  CompatitorMarket,
  CompatitorType,
  TA_RN,
  DATA_SOURCE
)
  SELECT
    A.TA TA_NAME,
    CASE
      WHEN A.RNK = 'null' then 99
      ELSE A.RNK
    END,
    A.BRAND_CODE,
    A.BRAND_NAME,
    REPLACE(NVL(A.CompatitorCN, ''), 'null', '') KEYCOMPATITORCN,
    REPLACE(NVL(A.CompatitorEN, ''), 'null', '') KEYCOMPATITOREN,
    REPLACE(NVL(A.CLASS, ''), 'null', '') CLASS,
    upper(A.IMSBRAND) IMSBRAND,
    REPLACE(NVL(A.CORP, ''), 'null', '') CORP,
    REPLACE(NVL(A.MARKET, ''), 'null', '') MARKET,
    A.MARKETDESC,
    A.DEFAULTFLAG,
    CASE
      WHEN REPLACE(NVL(A.VBP, ''), 'null', '') = '' THEN 'NonVBP'
      ELSE REPLACE(NVL(A.VBP, ''), 'null', '')
    END VBP,
    CASE
      WHEN REPLACE(NVL(A.VBP, ''), 'null', '') <> '' THEN 'VBP'
      ELSE 'NonVBP'
    END VBPFLAG,
    A.VALUETYPE,
    A.Strategicbrand,
    REPLACE(NVL(A.CompatitorMarket, ''), 'null', '') CompatitorMarket,
    REPLACE(NVL(A.CompatitorType, ''), 'null', '') CompatitorType,
    CASE
      WHEN A.TA = 'CV' THEN 2
      WHEN A.TA = 'DM' THEN 1
      WHEN A.TA = 'RD' THEN 3
      WHEN A.TA = 'RE' THEN 4
      WHEN A.TA = 'NEB' THEN 5
      WHEN A.TA = 'GI' THEN 6
      WHEN A.TA = 'ONC' THEN 7
      WHEN A.TA = 'RARE' THEN 8
    END TA_RN,
    CASE
      when A.DATA_SOURCE = 'IQVIA-County(Quarterly)' THEN 'IQVIA-COUNTY(Quarterly)'
      ELSE A.DATA_SOURCE
    END DATA_SOURCE
  FROM
    dm.DM_TD_EXTERNAL_KEYCOMPATITOR A