oracle table complex query

Description: In practical applications, it is often necessary to perform complex data statistics, and it is often necessary to display data from multiple tables.

1) Data grouping - max, min, avg, sum, count
? How to display the highest salary and lowest salary among all employees
SQL> select max(sal),min(sal) from emp;

? How to display the owner with the highest salary among all employees
SQL> select ename,sal from emp where sal=(select max(sal) from emp);

? How to display all the information of the owner with the highest salary among all employees
SQL> select * from emp where sal=(select max(sal) from emp);

? How to display all the information of the owner of the highest salary and lowest salary among all employees
SQL> select * from emp where sal=(select max(sal) from emp) or sal=(select min(sal) from emp);

? Display the average salary and salary sum of all employees
SQL> select avg(sal),sum(sal) from emp;

? Count how many employees there are
SQL> select count(*) from emp;

? Calculate how many employees have a superior
SQL> select count(mgr) from emp;



Extended requirements:
? Please show the name of the highest paid employee, job title
SQL> select ename,job from emp where sal=(select max(sal) from emp);

? Please display the information of employees whose salary is higher than the average salary
SQL> select * from emp where sal>(select avg(sal) from emp);

 

1) group by and having clause
group by is used to group the results of the query and statistics
having clause is used to limit the group display results

? How to display the average salary and maximum salary of each department
SQL> select avg(sal),max(sal ), deptno from emp group by deptno;
means to perform related calculations by department

? Display the average salary and minimum salary of each position in each department
SQL> select avg(sal),min(sal),deptno,job from emp group by deptno,job order by deptno;

?Display the average salary, minimum salary, maximum salary, and number of positions for each position in each department
SQL> select avg(sal),min(sal),max(sal), count(sal),deptno,job from emp group by deptno,job order by deptno;

?Display the department number and its average salary with an average salary lower than 2000 (using having)
SQL> select avg(sal),deptno from emp group by deptno having avg(sal)<2000;

The role of having is to do secondary screening

? Show the department with MANAGER and its maximum salary and minimum salary
SQL> select avg(sal),min(sal),max(sal),deptno,job from emp group by deptno,job having job='MANAGER';

? Display the department number with an average salary higher than 2000 and a PRESIDENT job
SQL> select deptno from emp group by deptno, job having avg(sal)>2000 and job='PRESIDENT';

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327037656&siteId=291194637