oracle 树结构数据统计(合计)

树(三层)结构数据统计

#{policeNum}传入树结构code

/*-----三级树结构数据统计(合计)-----*/
with 
/*基础数据准备*/
tp_aj as(
       SELECT gt.pid, gt.type, it.name as policename,gt.policenum policenum, it.deptid,it.status
  FROM (SELECT *
          FROM (SELECT g.updatime,g.obj_id pid,g.gps_x x,g.gps_y y,g.creatime,g.imei,g.remark,g.policenum,g.type,
                       row_number() over(partition by policenum order by updatime desc) rm
                  FROM T_DEVICE_GPS_LAST g
                 WHERE g.gps_x > 0
                   AND g.gps_y > 0
                   AND g.gps_x IS NOT NULL
                   AND g.gps_y IS NOT NULL
                   AND g.policenum IS NOT NULL
                 --  AND g.updatime BETWEEN TO_CHAR(sysdate, 'yyyy-MM-dd') || ' 00:00:00' AND TO_CHAR(sysdate, 'yyyy-MM-dd') || ' 23:59:59' 
                 )
         WHERE rm = 1) gt,
       (SELECT name, policenum, type, deptId, pdid, status
          FROM (SELECT i.name,
                       i.policenum,
                       i.type,
                       i.deptid,
                       i.pdid,
                       i.status,
                       row_number() over(partition by policenum order by time desc) rm
                  FROM REPORT_INFO i)
         WHERE rm = 1) it
 WHERE gt.policenum = it.policenum AND (it.status = '01' OR it.status = '04')  
),

/*---------------------类型分析统计----------------------*/
tp_aj_g1 as (
     select
          a.deptid dm,
         /*民警-接处警*/ count(case when a.type='01' and length(a.policenum)=6  then 1 end) jcj_mj,
         /*辅警-接处警*/ count(case when a.type='01' and length(a.policenum)>6  then 1 end) jcj_fj
        /*.......repeat..........*/
        
     from tp_aj a
    group by a.deptid
)
/*----------------------树结构正式统计----------------------*/
select md.dm "dm",
      decode(md.lvl, 2, md.mc, 1, '合计', md.mc) "mc",
      sum(jcj_mj_single) "jcj_mj_sum",
      sum(jcj_fj_single) "jcj_fj_sum"
       /*.......repeat..........*/
        
      from
        (
        select d.deptid dm,d.alias mc,d.sortnum sort_by,level lvl,
          case when connect_by_isleaf = 1 then nvl(g1.jcj_mj, 0) when level = 1 then sum(nvl(g1.jcj_mj,0)) over() when level = 2 then sum(nvl(g1.jcj_mj, 0)) over(partition by decode(level, 2, d.deptid,d.parentid)) end jcj_mj_single ,
          case when connect_by_isleaf = 1 then nvl(g1.jcj_fj, 0) when level = 1 then sum(nvl(g1.jcj_fj,0)) over() when level = 2 then sum(nvl(g1.jcj_fj, 0)) over(partition by decode(level, 2, d.deptid,d.parentid)) end jcj_fj_single         
          /*.......repeat..........*/
          from  t_fcpt_region d
          left join tp_aj_g1 g1 on g1.dm = d.deptid
        start with d.deptid = nvl(#{policeNum}, '320500000000')
        connect by prior d.deptid = d.parentid
        )
        md
where 1 = 1 and md.lvl in (1, 2)
group by md.dm, decode(md.lvl, 2, md.mc, 1, '合计', md.mc), md.sort_by
order by length(md.dm) desc, md.sort_by


result

你可能感兴趣的:(oracle 树结构数据统计(合计))