select
    e.organ_code, e.organ_name, e.comm_id, e.comm_name
     , case when project_name like '%撤场%' then '撤场' else '在管' end is_in_manage
     , case when a.status_id in (5,6) then '诉讼'
            when a.status_id in (4,7) then '非诉'
            else c.case_type end is_lawsuit
     , sum(a.owed_amt) trans_amt
     , count(distinct a.belong_resource) trans_household_num
     , sum(d.payment_coll_amt) payment_coll_amt
     , count(distinct d.belong_resource) payment_coll_num
     , b.apply_date ymd
     , sum(datediff(ifnull(str_to_date(c.wjsj,'%Y-%m-%d'),current_date()),str_to_date(b.apply_date,'%Y-%m-%d'))) trans_duration
from (select * from dwd_law_owed_info_d where status_id in (0,4,5,6,7,8,9,10)) a
         left join (select trans_payment, apply_date from dwd_law_trans_record_d) b
                   on a.id = b.trans_payment
         left join (select id, belong_resource, case_type, wjsj from dwd_law_case_info_d where status not in('作废','草稿') and belong_resource != '108926') c
                   on a.belong_resource = c.belong_resource
         left join (select payment_coll_date, case_name, payment_coll_amt, belong_resource from dwd_law_payment_collection_d) d
                   on c.id = d.case_name
         left join (select distinct organ_code, organ_name, comm_id, comm_name from dim_organ_mapping) e
                   on a.project_code = e.comm_id
group by 1,2,3,4,5,6,11