select
    ${if(len(p_area) == 0,"organ_name","comm_name")} as p_area  -- 片区/项目
     ,STR_TO_DATE(time, '%Y%m%d') as time -- 日期
     ,SUM(manualOutNum) AS manualOutNum   -- 出口手动抬杆数
     ,CASE WHEN SUM(carflow) = 0 THEN 0
           ELSE sum(manualNum) / SUM(carflow)
           END AS exceptionRate
from dw.dwd_engine_stat_exception_rate_d
where 1=1
${IF(LEN(p_area)!=0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
${IF(LEN(startdate)>0,"AND time >= '"+FORMAT(startdate,"yyyyMMdd")+"'","")}
${IF(LEN(enddate)>0,"AND time <= '"+FORMAT(enddate,"yyyyMMdd")+"'","")}
${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
GROUP BY
${if(len(p_area) == 0,"organ_name","comm_name")}
,STR_TO_DATE(time, '%Y%m%d')

select
    ${if(len(p_area)>0, "comm_name organ_name","organ_name organ_name")}
     , sum(manualOutNum) manualOutNum
     , sum(carflow) carflow
     , sum(manualOutNum) / sum(carflow) exceptionRate
 from dws_engine_stat_exception_rate_w
where yw = (select distinct yw from dws_engine_stat_exception_rate_w order by yw desc limit 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
    ${if(len(p_area)>0, "comm_name","organ_name")}