SELECT
${if(len(p_area) == 0,"A.organ_name","A.comm_name")} as p_area  -- 片区/项目
,SUM(A.tousu_incident_num) AS tousu_incident_num -- 投诉量
,sum(B.ROOM_NUM) AS ROOM_NUM -- 户数
,CASE WHEN sum(B.ROOM_NUM) = 0 THEN 0
      ELSE SUM(A.tousu_incident_num) / sum(B.ROOM_NUM) * 10000
      END AS AVG_INCIDENT_NUM -- 每万户均投诉量
FROM
(
    SELECT
     organ_code
    ,organ_name
    ,comm_id
    ,comm_name
  --  ,incident_ym
    ,SUM(IFNULL(tousu_incident_num,0))  AS tousu_incident_num -- 投诉量
    FROM dw.dws_estate_incident_info_m
    where incident_ym = '${REPLACE(p_ym,"-","")}'
    ${IF(LEN(p_area)>0," and organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
    ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
    GROUP BY
    organ_code
    ,organ_name
    ,comm_id
    ,comm_name
    having SUM(IFNULL(tousu_incident_num,0)) !=0
)A
LEFT JOIN
(
    SELECT
    T1.organ_code       AS ORGAN_CODE -- 片区ID
    ,T1.comm_id         AS COMM_ID    -- 项目ID
    ,count(T2.RoomName) AS ROOM_NUM   -- 户数
    FROM dw.dim_organ_mapping T1
    INNER JOIN dim_room_d T2
    ON T1.comm_id = T2.CommID
    WHERE 1 = 1
     ${IF(LEN(p_area)>0," and organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
     ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
    GROUP BY
    T1.organ_code
    ,T1.comm_id
)B
ON A.comm_id = B.COMM_ID
AND A.organ_code = B.ORGAN_CODE
GROUP BY
${if(len(p_area) == 0,"A.organ_name","A.comm_name")}