问题
SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO, o.SUBTOTAL,
PERCENT_RANK() OVER ( partition by e.EMPLOYEE_NO ORDER BY e.EMPLOYEE_NO ASC) AS percent
FROM EMPLOYEE e
INNER JOIN BRANCH b
ON e.BRANCH_NO = b.BRANCH_NO
INNER JOIN ORDERS o
ON o.BRANCH_NO = b.BRANCH_NO
ORDER BY b.BRANCH_NO
FETCH FIRST 10 PERCENT ROWS ONLY;
- I am trying to retrieve top 10 percent of each branch.
- PL SQL
回答1:
You can use analytical functions
as following:
Select employee_no,
Fname,
Lname,
employee_total_order,
Branch_no
From
(SELECT e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO,
SUM(o.SUBTOTAL) AS employee_total_order,
Count(distinct e.employee_no)
over (partition by b.branch_no) as total_emp,
Row_number()
over (partition by b.branch_no order by SUM(o.SUBTOTAL) desc nulls last) as rn
FROM EMPLOYEE e
INNER JOIN BRANCH b
ON e.BRANCH_NO = b.BRANCH_NO
INNER JOIN ORDERS o
ON o.BRANCH_NO = b.BRANCH_NO
Group by e.EMPLOYEE_NO, e.FNAME, e.LNAME, b.BRANCH_NO)
Where rn/total_emp <= 0.1
or rn = 1 -- this condition is used to fetch atleast one employee
-- if branch has less than 10 employees
Cheers!!
来源:https://stackoverflow.com/questions/60310214/fetch-rownum-first-n-percent-from-each-branch-branch-no-i-am-trying-to-retr