Oracle queries departments with the minimum number of employees

Source: Internet
Author: User
-- Department table createtablet_dept (d_idnumberprimarykey, d_namevarchar2 (20); createsequencedept_seq

-- Department table create table t_dept (d_id number primary key, d_name varchar2 (20); create sequence dept_seq

Purpose: To query the departments with the minimum number of employees

Knowledge Point: grouping function, sorting, subquery, rownum

The SQL statement is as follows:

Analysis:

Step 1: select count (*) coun, d_id deptId from t_emp group by d_id to query the t_emp table, and query the number of people in each department by d_id.

Step 2: select count (*) coun, d_id deptId from t_emp group by d_id order by coun asc and then orderby coun asc. In this way, the numbers are sorted in ascending order, in this way, the first one is the minimum number of people.

Step 3: subquery, select * from (select count (*) coun, d_id deptId from t_emp group by d_id order by coun asc) where rownum = 1, oracle does not support select top 1. to retrieve the first data, we need to use the rownum column allocated to the query by using sort El. If where rownum = 1, we get the first data.

The result is as follows:

---------------------------------------

Counn deptid

---------------------------------------

2 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.