-- 【单位面积能耗同环比】

select
    A.organ_code      AS organ_code
     , A.organ_name      AS organ_name
     , A.comm_id         AS comm_id
     , A.comm_name       AS comm_name
     , A.MeterType       AS MeterType
     , A.list_ym         AS list_ym
     , A.Dosage          AS Dosage
     , A.Amount          AS Amount
     ,IF(B.ContractArea = 0,0,A.Dosage / B.ContractArea) AS DOSAGE_PER_SQUARE_METER
from
    (
        SELECT
            organ_code
             , organ_name
             , comm_id
             , comm_name
             , MeterType
             , list_ym
             , Dosage
             , Amount
        FROM dws_engine_meter_dosage_m
        ${IF(p_type = "环比","/*","")}
        where 1=1
          AND list_ym <> DATE_FORMAT(CURDATE(), '%Y%m')
          AND list_ym >= '${FORMAT(MONTHDELTA(CONCATENATE(p_ym,"-01"),-60),"yyyyMM")}'
            ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
            ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
            ${IF(LEN(p_ym)>0," AND right(list_ym,2) ='" +right(p_ym,2) + "'","")}
          and MeterType in ('水表','电表')
        order by list_ym asc
            ${IF(p_type = "环比","*/","")}

            ${IF(p_type = "环比","","/*")}
        where left(list_ym,4) = ${left(p_ym,4)}
          AND list_ym <> DATE_FORMAT(CURDATE(), '%Y%m')
          and MeterType in ('水表','电表')
            ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
            ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
        ORDER BY list_ym ASC
            ${IF(p_type = "环比","","*/")}
    )A
        LEFT JOIN
    (
        select
            CommId  -- 项目id
             ,SUM(ContractArea) AS  ContractArea-- 合同面积（建筑面积）
        from dim_project_base_info_d
        GROUP BY
            CommId
    )B
    ON A.comm_id = B.CommId
ORDER BY A.list_ym,A.MeterType
;