Oracle SQL统计各单位及其子级单位用户总数
业务场景:最近帮同事写一个sql,业务是统计各个单位及其子单位用户总数,听起来是挺容易的,所以拿起键盘就是敲:
select sum(t.ucount) from (select count(1) as ucount, uinfo.unit_code, uinfo.unit_name from t_user bs inner join (select unit_code, unit_name from t_unit_info start with unit_code = #{unitCode} connect by prior unit_code = para_unit_code) uinfo on bs.unit_code = uinfo.unit_code group by uinfo.unit_code, uinfo.unit_name) t;
不过这个只能传个顶级单位编码,一个一个查,这样肯定很耗时,所以还是自己想太简单了,摸索了好一阵子,想到方法:
①、新建一个函数,传一个顶级单位编码,通过函数统计本单位及其子单位的用户总数
create or replace function FU_UNIT_USER_COUNT(unitCode in varchar2) RETURN NUMBER IS v_Value number(9,1); BEGIN select sum(t.ucount) into v_Value from (select count(1) as ucount, uinfo.unit_code, uinfo.unit_name from t_user bs inner join (select unit_code, unit_name from lzcity_approve_unit_info start with unit_code = unitCode connect by prior unit_code = para_unit_code) uinfo on bs.unit_code = uinfo.unit_code group by uinfo.unit_code, uinfo.unit_name) t; RETURN v_Value; END;
测试函数是否建立成功:
select FH_UNIT_USER_COUNT('15803') from dual;
②、调用函数,传顶级单位编码进行统计
select FH_UNIT_USER_COUNT(uinfo.unit_code) as 用户总数, uinfo.unit_code as 单位编码, uinfo.unit_name as 厅单位名称 from t_unit_info uinfo group by uinfo.unit_code, uinfo.unit_name order by 用户总数 desc nulls last