This article brings you relevant knowledge about Oracle advanced queries, including group queries, multi-table queries and subqueries. I hope it will be helpful to everyone.

Oracle Advanced Query
Advanced query is widely used in the development process of database, from group query, multi-table query and sub-query Introduce Oracle's advanced queries in three aspects.
Grouping query
Grouping query is to group according to certain rules. After grouping, the data will be aggregated. Aggregation functions need to be used, but grouping is not necessary to use aggregate functions. The keyword for grouping is group by.
Commonly used aggregation functions include: maximum max(), minimum min(), average avg(), sum sum(), and statistical number count()
Use of count function Null values will be automatically ignored when naming the column

nvl function can prevent count from automatically ignoring null values. Its function is to return 0 when comm is empty, because 0 is non-empty. So it will go into the statistical total.

group by subquery
All columns in the select list that are not included in the aggregate function should be included in the group by in clause.
Single column grouping
Find the average salary of each department, display the department number and the average salary of the department.
select deptno,avg(sal) from emp group by deptno order by deptno
Multiple column grouping
Statistics on the total salary of employees by department and different positions
select detpno,job,sum(sal) from emp group by deptno,job order by deptno
Filter grouping
Use of having clause
The difference between where and having
- Aggregation functions cannot be used in the where clause, filter first and then group
- having sub Aggregation functions can be used in the sentence to group first and then filter
Note: From the perspective of SQL optimization, try to use where, because where greatly reduces the number of grouped records, thus Improve efficiency.
Find the departments whose average salary is greater than 2000
select deptno,avg(sal) from emp where(avg(sal)) > 2000 group by deptno

The aggregate function cannot be used in the where clause, so an error is reported, change it to having The xxx clause is sufficient.
select deptno,avg(sal) from emp group by deptno having(avg(sal)) > 2000
Use order by
in the group query to find the average salary of each department, display the department number, and the average salary of the department, arranged in ascending order of salary.
select deptno,avg(sal) from emp group by deptno order by avg(sal)
You can also sort by the alias of the column
select deptno,avg(sal) avgsal from emp group by deptno order by avgsal
You can also sort by the serial number of the column. The average salary is the second column
select deptno,avg(sal) from emp group by deptno order by 2
Just add desc in descending order
select deptno,avg(sal) from emp group by deptno order by 2 desc
Nesting of grouping functions
Find the maximum value of the average salary of the department
select max(avg(sal)) from emp group by deptno
group by statement enhancement
Mainly used in the group by statement report function
Each department, install different positions, find the total salary, department summary, summary.

You can use the rollup function
select deptno,job,sum(sal) from emp group by rollup(deptno,job)

and then set the display format. Break on deptno means that the same department number only Display one, skip 1 means there is a blank line between different department numbers.

Improve report display
Add title, page number, etc.
ttitle col 15 'My Report' col 35 sql.pno
Set the title, empty 15 columns to display my report, and then empty 35 columns to display the page number
col deptno heading department number
col job heading position
col sum(sal) heading Total salary
Set column headers for the above 3 lines
break on deptno skip 1
Set the display format, the same department number only Display one, with a blank line between different department numbers
Save these settings to a sql file (note that it must be changed to ANSI encoding, otherwise garbled characters will appear and the settings will be invalid), and then read and executed through the get command. Execute the query statement again and get the following report. If multiple pages appear, in order to display them beautifully, you can set one page to display more lines, for example, set each page to display 100 lines: set pagesize 100

多Table Query
The above examples all query data from a single table. Let’s start with querying data from multiple tables.
In order to avoid the Cartesian set, you can add valid connection conditions to where. Under actual circumstances, the use of the Cartesian complete set should be avoided.

等值连接
实例:查询员工信息,要求显示:员工号,姓名,月薪,部门名称
需要查询员工表和部门表,通过部门号进行等值连接查询,where xxx=xxx
select e.empno,e.ename,e.sal,d.dname from emp e,dept d where e.deptno=d.deptno
不等值连接
示例:查询员工信息,要求显示:员工号,姓名,月薪,薪水级别
需要查询员工表和薪水等级表,通过薪水等级上下限进行不等值连接查询。where xxx between xxx and xxx,注意:小值在between前面,大值在between后面
select e.empno,e.ename,e.sal,s.grade from emp e,salgrade s where e.sal between s.losal and s.hisal
外连接
示例:按部门统计员工人数,要求显示:部门号,部门名称,人数
需要查询部门表和员工表
以下是通过等值连接的方式查询,虽然总人数没有问题,但是少了一个部门,因为一个部门没有员工。
select d.deptno 部门号,d.dname 部门名称,count(e.empno) 人数 from emp e,dept d where e.deptno=d.deptno group by d.deptno,d.dname

外连接一般通过join来实现,一张图看懂SQL的各种join用法。

使用join语句重新实现示例功能
select d.deptno 部门号,d.dname 部门名称,count(e.empno) 人数 from dept d left join emp e on d.deptno=e.deptno group by d.deptno,d.dname
自连接
示例:查询员工姓名和员工的老板姓名
核心:通过别名,将同一张表视为多张表
select e.ename 员工姓名,b.ename 老板姓名 from emp e, emp b where e.mgr=b.empno
这种方式会产生笛卡尔集,不适合大表的查询,可以使用层次查询来解决。connect by xxx start with xxx
level是层次查询提供的伪列,需要显示使用才会查询这个伪列。
select level,empno,ename,sal,mgr from emp connect by prior empno=mgr start with mgr is null order by 1
子查询
子查询语法中的小括号
必须要有小括号,书写风格要清晰如下图所示:
示例:查询比FORD工资高的员工
select * from emp where sal > (select sal from emp where ename='FORD')
可以使用子查询的位置
select,from,where,having
select位置的子查询只能是单行子查询,也就是只能返回一条结果
select empno,ename,sal,(select job from emp where empno='7839') job from emp
having位置的子查询
示例:查找部门平均工资大于30号部门最大工资的部门号及其平均工资
select deptno,avg(sal) from emp group by deptno having avg(sal) > (select max(sal) from emp where deptno=30)
from位置的子查询
查询结果也可以当成表
select * from (select empno,ename,sal from emp)
增加1列年薪,使用sal*12得到年薪
select * from (select empno,ename,sal,sal*12 annsal from emp)
主查询和子查询可以不是同一张表
示例:查询部门名称是SALES的员工信息
使用子查询的方式:
select * from emp where deptno=(select deptno from dept where dname='SALES')
使用多表查询的方式:
select e.* from emp e, dept d where e.deptno=d.deptno and d.dname='SALES'
子查询的排序
一般不在子查询中,使用排序;但在Top-N分析问题中,必须对子查询排序
示例:找到员工表中工资最高的前三名,如下格式:

rownum,行号,oracle自动为表分配的伪列。
- 行号永远按照默认的顺序生成
- 行号只能使用,>=
select rownum,empno,ename,sal from (select * from emp order by sal desc) where rownum<h3 id="strong-子查询执行顺序-strong"><strong>子查询执行顺序</strong></h3><p>一般先执行子查询,再执行主查询;单相关子查询例外。</p><p>相关子查询示例:找到员工表中薪水大于本部门平均薪水的员工</p><pre class="brush:php;toolbar:false">select empno,ename,sal,(select avg(sal) from emp where deptno=e.deptno) avgsal from emp e where sal > (select avg(sal) from emp where deptno=e.deptno)
单行子查询和多行子查询
单行子查询返回一个结果,只能使用单行操作符;
多行子查询返回多个结果,只能使用多行操作符。
单行操作符:
| 操作符 | 含义 |
|---|---|
| = | 等于 |
| > | 大于 |
| >= | 大于等于 |
| 小于 | |
| 小于等于 | |
| 不等于 |
多行操作符:
| 操作符 | 含义 |
|---|---|
| in | 等于列表中的任何一个 |
| any | 和子查询返回的任意一个值比较 |
| all | 和子查询返回的左右值比较 |
单行子查询示例1:
查询员工信息,要求:
职位与7566员工一样,薪水大于7782员工的薪水
select * from emp where job=(select job from emp where empno=7566) and sal >(select sal from emp where empno=7782)
单行子查询示例2:
查询最低工资大于20号部门最低工资的部门号和部门的最低工资
select deptno,min(sal) from emp group by deptno having min(sal) > (select min(sal) from emp where deptno=20)
多行子查询示例:
查询部门名称是SALES和ACCOUNTING的员工信息
使用多行子查询的方式:
select * from emp where deptno in (select deptno from dept where dname='SALES' or dname='ACCOUNTING')
使用多表查询的方式:
select e.* from emp e, dept d where e.deptno=d.deptno and (d.dname='SALES' or d.dname='ACCOUNTING')
子查询中的空值问题
查询不是老板的员工
注意:当子查询中包含null值时,不要使用not in。
a not in (10,20,null)
a != 10 and a != 20 and a != null, a != null 永远不成立,所以整个表达式永远返回false。
可以在子查询中把null值过滤掉再使用not in。
select * from emp where empno not in (select mgr from emp where mgr is not null)
推荐教程:《Oracle教程》
The above is the detailed content of Let's talk about Oracle advanced queries (detailed examples). For more information, please follow other related articles on the PHP Chinese website!
What Does Oracle Offer? Products and Services ExplainedApr 16, 2025 am 12:03 AMOracleoffersacomprehensivesuiteofproductsandservicesincludingdatabasemanagement,cloudcomputing,enterprisesoftware,andhardwaresolutions.1)OracleDatabasesupportsvariousdatamodelswithefficientmanagementfeatures.2)OracleCloudInfrastructure(OCI)providesro
Oracle Software: From Databases to the CloudApr 15, 2025 am 12:09 AMThe development history of Oracle software from database to cloud computing includes: 1. Originated in 1977, it initially focused on relational database management system (RDBMS), and quickly became the first choice for enterprise-level applications; 2. Expand to middleware, development tools and ERP systems to form a complete set of enterprise solutions; 3. Oracle database supports SQL, providing high performance and scalability, suitable for small to large enterprise systems; 4. The rise of cloud computing services further expands Oracle's product line to meet all aspects of enterprise IT needs.
MySQL vs. Oracle: The Pros and ConsApr 14, 2025 am 12:01 AMMySQL and Oracle selection should be based on cost, performance, complexity and functional requirements: 1. MySQL is suitable for projects with limited budgets, is simple to install, and is suitable for small to medium-sized applications. 2. Oracle is suitable for large enterprises and performs excellently in handling large-scale data and high concurrent requests, but is costly and complex in configuration.
Oracle's Purpose: Business Solutions and Data ManagementApr 13, 2025 am 12:02 AMOracle helps businesses achieve digital transformation and data management through its products and services. 1) Oracle provides a comprehensive product portfolio, including database management systems, ERP and CRM systems, helping enterprises automate and optimize business processes. 2) Oracle's ERP systems such as E-BusinessSuite and FusionApplications realize end-to-end business process automation, improve efficiency and reduce costs, but have high implementation and maintenance costs. 3) OracleDatabase provides high concurrency and high availability data processing, but has high licensing costs. 4) Performance optimization and best practices include the rational use of indexing and partitioning technology, regular database maintenance and compliance with coding specifications.
How to delete oracle library failureApr 12, 2025 am 06:21 AMSteps to delete the failed database after Oracle failed to build a library: Use sys username to connect to the target instance. Use DROP DATABASE to delete the database. Query v$database to confirm that the database has been deleted.
How to create cursors in oracle loopApr 12, 2025 am 06:18 AMIn Oracle, the FOR LOOP loop can create cursors dynamically. The steps are: 1. Define the cursor type; 2. Create the loop; 3. Create the cursor dynamically; 4. Execute the cursor; 5. Close the cursor. Example: A cursor can be created cycle-by-circuit to display the names and salaries of the top 10 employees.
How to export oracle viewApr 12, 2025 am 06:15 AMOracle views can be exported through the EXP utility: Log in to the Oracle database. Start the EXP utility, specifying the view name and export directory. Enter export parameters, including target mode, file format, and tablespace. Start exporting. Verify the export using the impdp utility.
How to stop oracle databaseApr 12, 2025 am 06:12 AMTo stop an Oracle database, perform the following steps: 1. Connect to the database; 2. Shutdown immediately; 3. Shutdown abort completely.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use







