17,082
社区成员
发帖
与我相关
我的任务
分享
WITH tmp AS (
SELECT r.*, percent_rank() OVER (PARTITION BY deptcode ORDER BY dbms_random.value()) AS percent
FROM reginfo r
WHERE regdate BETWEEN to_date('2017-01-01', 'YYYY-MM-DD') AND to_date('2018-01-01', 'YYYY-MM-DD')
)
SELECT *
FROM tmp
WHERE tmp.percent <= 0.1;
2.取各个科室最早注册的 10%:
WITH tmp AS (
SELECT r.*, percent_rank() OVER (PARTITION BY deptcode ORDER BY regdate) AS percent
FROM reginfo r
WHERE regdate BETWEEN to_date('2017-01-01', 'YYYY-MM-DD') AND to_date('2018-01-01', 'YYYY-MM-DD')
)
SELECT *
FROM tmp
WHERE tmp.percent <= 0.1;
3. 取各个科室最晚注册的 10%:
WITH tmp AS (
SELECT r.*, percent_rank() OVER (PARTITION BY deptcode ORDER BY regdate DESC) AS percent
FROM reginfo r
WHERE regdate BETWEEN to_date('2017-01-01', 'YYYY-MM-DD') AND to_date('2018-01-01', 'YYYY-MM-DD')
)
SELECT *
FROM tmp
WHERE tmp.percent <= 0.1;
备注:把 r.* 改成表 reginfo 中需要显示的各个字段名称;percent_rank() 函数的文档:https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/PERCENT_RANK.html#GUID-66A868F5-9EBA-482A-BF8C-09300B9EE165select *
from (select t1.*,
percent_rank() over(partition by deptcode order by ora_hash(t1.rowid || trunc(dbms_random.value * 10000), 10000)) pp
from reginfo t1
where t1.regdate between trunc(sysdate, 'y') and sysdate
) t1
where t1.pp < 0.1;
declare
-- Local variables here
xempno varchar2(10);
xename varchar2(10);
xdeptno varchar2(10);
begin
--首先創建一個表,用來裝每個科室的10%的人員,我這裡創建的是T1
for r1 in (select deptno,round(count(empno) * 0.1) qty
from emp a
where a.hiredate between to_date('xxxxxxxx', 'yyyy/mm/dd') and
to_date('zzzzzzzz', 'yyyy/mm/dd')
group by deptno)
loop
select empno,ename,deptno into xempno,xename,xdeptno from emp where deptno = r1.deptno
and rownum <=r1.qty;
insert into t1
values(xempno,xename,xdeptno);
commit;
end loop;
end;
接着查询T1表就好了