Oracle basic statement Learning (3) subquery

Source: Internet
Author: User
1 subquery ex: Find the name, whose salary is above the average salary selectename, salfromempwheresal (selectavg (sal) fromemp); 2. See table subquery for the persons with the highest salary in each department. intuitive method selectename, salfromempwheresalin (selectmax (sal) fromempgroupbydept

1 subquery ex: name, whose salary is above the average wage select ename, sal from emp where sal (select avg (sal) from emp ); 2. See the subquery for the persons with the highest salaries in each department. intuitive method select ename, sal from emp where sal in (select max (sal) from emp group by dept

1 subquery

Ex: name. The salary is above the average salary.

Select ename, sal from emp where sal> (select avg (sal) from emp );


2. See table subquery.

Query the persons with the highest salaries in each department.

Intuitive method select ename, sal from emp where sal in (select max (sal) from emp group by deptno );

This query method may cause an error. If the highest salary of Department A is 5000 while that of department A's p employee is 3000, which is equal to the highest salary of department B, the employee will also be shown;


The correct method is as follows:

First, we can find that select max (sal) from emp group by deptno can get a table, as shown in


You only need to find the employees with the same department and salary in emp.


The statement is as follows:

1 select ename, sal from emp

2 join (select max (sal) max_sal, deptno from emp group by deptno) t // connect table

3 on (emp. sal = t. max_sal and emp. deptno = t. deptno); // connection Condition



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.