简体   繁体   中英

How do I select top rows in SQL

I have a code that outputs Department Names and their number of workers.

SELECT department_name,COUNT (employee_id) FROM EMPLOYEES  
JOIN DEPARTMENTS  
ON employees.department_id=departments.department_id
GROUP BY department_name 
ORDER BY count(employee_id) DESC

输出

I want to select the first three department names that have the largest number of workers. . When I WHERE , I get three rows, but the output is not true.

SELECT department_name,COUNT (employee_id) FROM EMPLOYEES  
JOIN DEPARTMENTS  
ON employees.department_id=departments.department_id
WHERE rownum <= 4
GROUP BY department_name 
ORDER BY count(employee_id) DESC

输出

What can you recommend to me about this issue? Also, I will use this query in a PL/SQL block. THANKS!

That rownum clause happens before the sort. You can either use

fetch first 3 rows only

after the order by clause, if using Oracle 12c or above, or with rownum use a subquery -

select * from (
    your query here
) 
where rownum < 4;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM