-- 【1_report_御和泰销售情况】


SELECT
     T1.organ_name      AS ORGAN_NAME
     ,T1.comm_name      AS COMM_NAME
     ,T1.FINISH_RATE 	AS FINISH_RATE
     ,T1.sale_target 	AS SALE_TARGET
     ,T1.sale_amt 		AS SALE_AMT
     ,ROW_NUMBER() OVER (ORDER BY T1.FINISH_RATE DESC) AS RK
FROM
    (
        SELECT

            A.comm_name
            ,A.organ_name
             ,SUM(B.sale_target) AS sale_target
             ,IFNULL(SUM(A.sale_amt) + SUM(B.sale_fact),0) AS sale_amt
             ,CASE WHEN SUM(B.sale_target) = 0 THEN 0
                   ELSE IFNULL(SUM(A.sale_amt) + SUM(B.sale_fact),0) / SUM(B.sale_target) END  AS FINISH_RATE
        FROM
            (
                select
                    organ_code
                     ,organ_name
                     ,comm_id
                     ,comm_name
                     ,sum(case when create_ym = '202406' then 0 else yht_amt end) sale_amt -- 202406填报数据为线下+线下，所以不取线上数据
                from dw.dws_innoveco_new_retail_m -- 新零售月汇总
                where create_ym = '${REPLACE(p_ym,"-","")}'
                group by
                    organ_code
                       ,organ_name
                       ,comm_id
                       ,comm_name
            )A
                LEFT JOIN
            (
                SELECT
                    organ_code
                     ,organ_name
                     ,comm_id
                     ,comm_name
                     ,SUM(IFNULL(index_yuhetai_target,0))*10000 AS  sale_target
                     ,SUM(index_yuhetai_fact)*10000 AS sale_fact
                FROM dw.ods_innoveco_offlinesales
                WHERE `year_month` = '${REPLACE(p_ym,"-","")}'
                GROUP BY
                    organ_code
                       ,organ_name
                       ,comm_id
                       ,comm_name
            )B
            ON A.organ_code = B.organ_code
                AND A.comm_id = B.comm_id
        WHERE 1=1
            ${IF(LEN(p_area)>0," AND A.organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
              ${if(left(fine_role,2)=="项目","and B.comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
        GROUP BY
            A.comm_name
                ,A.organ_name
    )T1

