-- 【1_report_多径回款情况】


SELECT
    business_code      -- 业务域code
     ,organ_code         -- erp片区code
     ,organ_name         -- erp片区名称
     ,comm_id            -- 项目id
     ,comm_name          -- 项目名称
     ,index_type         -- 多经类别(社商/ 新零售、美居、附属资源/ 空间运营、资产运营/ 资产租售)
     ,index_receivable   -- 应收值
     ,index_receipts     -- 实收值
     ,index_not_receipts -- 未回款数
     ,collection_rate    -- 回款率
FROM dw.ods_caiwu_profit
WHERE (index_receivable <> 0 OR index_receipts <> 0 OR index_not_receipts <> 0)
  AND `year_month` =  '${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)+"'","")}
    ${IF(LEN(p_type)>0," AND index_type IN ('"+JOINARRAY(p_type,"','")+"')", "")}


-- 【2_业务条线】
SELECT
    DISTINCT
    index_type
FROM dw.ods_caiwu_profit
;

-- 【1_report_欠费下钻明细】
SELECT
 A.OrganCode   AS OrganCode -- 片区编码
,A.OrganName   AS OrganName -- 片区名称
,A.CommID      AS CommID    -- 项目id
,A.CommName    AS CommName  -- 项目名称
,A.CustName    AS CustName  -- 客户姓名 商户
,SUM(A.recev_amount)  AS recev_amount-- 应收金额
,A.AccountsDueDate  AS AccountsDueDate -- 应收日期
,SUM(A.paid_amount)  AS paid_amount -- 实收金额 回款金额
,SUM(A.recev_amount) - SUM(A.paid_amount) AS Arrears_amount -- 欠费金额
,IF(SUM(A.recev_amount) = 0,0,SUM(A.paid_amount) /SUM(A.recev_amount))  AS PAID_AMOUNT_RATE
FROM
(
    SELECT
     OrganCode               -- 片区编码
    ,OrganName              -- 片区名称
    ,CommID                 -- 项目id
    ,CommName               -- 项目名称
    ,CustName               -- 客户姓名 商户
    ,SUBSTR(AccountsDueDate,1,10)   AS AccountsDueDate     -- 应收日期
    ,CorpCostID
    ,CASE WHEN BussType IN('新增','删除') THEN DealAmount ELSE 0 END AS recev_amount -- 应收金额
    ,CASE WHEN BussType IN('实收','撤销实收') THEN DealAmount ELSE 0 END AS paid_amount -- 实收金额
    FROM dw.ods_erp_tb_hspr_feesserial_${p_comm_id}_d
    WHERE left(AccountsDueDate,7) = '${p_ym}'
    ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
    ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
)A
JOIN
(
    SELECT
    a.CorpCostID
    ,a.CostName
    FROM
    (
        select
        CorpCostID
        ,CostCode
        ,CostName
        from dw.dim_corp_cost_item_d -- 总部费用科目
        where length(CostCode) != 4
    ) a
    left join
    (
        select
         CorpCostID
        ,CostCode
        from dim_corp_cost_item_d
        where length(CostCode) = 4
    ) b
    on left(a.CostCode,4) = b.CostCode
    where b.CostCode  = '0007'
)B
ON A.CorpCostID = B.CorpCostID
GROUP BY
A.OrganCode
,A.OrganName
,A.CommID
,A.CommName
,A.CustName
,A.AccountsDueDate




