我正在使用我创建的一个表(实际上是一个视图),它包含三列:年份,分支,员工数量。
create table employee_count(
year varchar2(4),
branch varchar2(4),
employee_count int
);
insert into employee_count values('2014', '20', 5);
insert into employee_count values('2014', '201', 10);
insert into employee_count values('2014', '21', 5);
insert into employee_count values('2014', '2101', 10);
insert into employee_count values('2014', '2102', 5);
insert into employee_count values('2014', '22', 10);
insert into employee_count values('2014', '2201', 5);
insert into employee_count values('2014', '23', 10);
insert into employee_count values('2014', '2301', 5);
重要的是要知道分支列包含不同级别的组织。例如,20
是一个部门,201
是一个部门,2201
是一个部门。
我正在尝试构建一个查询,为我提供每个分支的总员工数以及整数的百分比。关于这一点的棘手部分是我希望能够传递一个参数来表示组织级别并接收组织不同级别的数据,结果显示子级别。
这是我的问题:
select sum(employee_count) as count,
round(100 * ratio_to_report (sum(employee_count)) over()) || '%' as percent,
substr(branch,0,length(:param) + 1) as branch,
year
from employee_count
where year = '2014' and branch like :param || '%'
group by substr(branch, 0, length(:param) + 1), year
order by branch;
如果我传递参数2
,这意味着整个组织都可以正常工作。然后我按预期收到我的结果:
COUNT PERCENT BRANCH YEAR
15 23% 20 2014
20 31% 21 2014
15 23% 22 2014
15 23% 23 2014
但是,当我通过某个特定部门时,请说21
作为参数,我不会收到部门21
内各级别的计数/百分比。
我想收到:
COUNT PERCENT BRANCH YEAR
5 25% 21 2014
10 50% 2101 2014
5 25% 2102 2014
相反,我收到了:
COUNT PERCENT BRANCH YEAR
5 25% 21 2014
15 75% 210 2014
所以基本上我正在尝试编写一个足够灵活的查询,以接受任何级别的组织代码作为参数,然后返回下面每个级别的计数/百分比。
有人能指出我正确的方向或让我知道这是否可能?
答案 0 :(得分:1)
尝试这样的事情:
select sum(employee_count) as count,
round(100 * ratio_to_report (sum(employee_count)) over()) || '%' as percent,
branch as branch,
year
from employee_count
where year = '2014' and branch like '21%'
group by branch, year
order by branch;