with one_to_many AS(
SELECT
a.username AS username -- 用户名
,SUBSTRING_INDEX(SUBSTRING_INDEX(a.mang_project, ',',b.help_topic_id + 1),',',-1) AS mang_project -- 管理项目名
FROM ods_one_to_many_perm a
JOIN mysql.help_topic b
on b.help_topic_id < (LENGTH(a.mang_project) - length(replace(a.mang_project,',','')) + 1)
WHERE a.username  = '${fine_username}'
)
select
    ${if(len(p_area) == 0,"organ_name","comm_name")} as p_area  -- 片区/项目
   --  organ_name      -- 片区名称
   -- ,comm_name       -- 项目名称
    ,sum(room_num) as room_num        -- 房间总数 【总户数】
    ,sum(check_ins_num) as check_ins_num   -- 入住数   【入住户数】
    ,case when sum(check_ins_num) = 0
              then 0
          else sum(check_ins_num) / sum(room_num)
    end as   occupancy_rate -- 入住率
from dws_operation_room_park_info_d
where 1=1
${IF(LEN(p_area)!=0," and organ_code IN ('"+p_area+"')","")}
-- ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
AND CASE WHEN (SELECT mang_project FROM ods_one_to_many_perm WHERE username  = '${fine_username}' AND mang_organ IS NULL) IS NOT NULL
         THEN comm_name IN (SELECT mang_project FROM one_to_many WHERE username  = '${fine_username}') 
          ELSE ${if(left(fine_role,2)=="项目","comm_name = '"+GETUSERDEPARTMENTS(3)+"'","1=1")} END

group by
${if(len(p_area) == 0,"organ_name","comm_name")}