1 子查询
表结构如下
需求
查询用户分数大于
其所在工作(job)分数的平均分
的所有grade的属性
,并且以id
的升序
排序
SQL语句
select t1.* from grade t1
where score>(select avg(score) from grade t2
where t1.job = t2.job
group by job)
order by t1.id;
注意的是where
子句一定要放在group by
子句前面
。
运行结果
2 子查询
表结构如下
需求
查询在2025-10-15以后
,同一个用户下单2个以及2个以上
状态为购买成功
的C++
课程或Java
课程或Python
课程的user_id
,并且按照user_id升序
排序
SQL语句
select user_id from (
select user_id, count(*) as num from order_info
where date>'2025-10-15'
and status='completed'
and product_name in ('C++', 'Java', 'Python')
group by user_id
) as t
where num>=2
order by user_id;
注意的是,where num>=2
要写在括号外面,且表要有别名
。
运行结果
3 子查询
表结构如下
需求
查询在2025-10-15以后
,同一个用户下单2个以及2个
以上状态为购买成功
的C++
课程或Java
课程或Python
课程的订单信息,并且按照order_info
的id升序
排序。
注意与前一个题目的区别。
SQL语句
select * from order_info
where user_id in (
select user_id from order_info oi
where date>'2025-10-15'
and product_name in ('C++','Java','Python')
and status='completed'
group by user_id
having count(*)>=2
)
and date>'2025-10-15'
and product_name in ('C++','Java','Python')
and status='completed'
order by id;
运行结果
4 子查询
表结构如下
需求
查询在2025-10-15以后
,同一个用户下单2个以及2个以上
状态为购买成功
的C++
课程或Java
课程或Python
课程的订单id
,是否拼团
以及客户端名字
信息,最后一列如果是非拼团订单,则显示对应客户端名字,如果是拼团订单,则显示NULL,并且按照order_info
的id升序
排序。
SQL语句
select o.id, o.is_group_buy, c.name as client_name from (
select * from order_info
where user_id in (
select user_id from order_info
where date>'2025-10-15'
and product_name in ('C++','Java','Python')
and status='completed'
group by user_id
having count(*)>=2
)
and date>'2025-10-15'
and product_name in ('C++','Java','Python')
and status='completed'
) as o
left join client c
on o.client_id = c.id
order by o.id;
这个语句是在第3个问题的SQL语句的基础
上添加了一个左连接
。
运行结果
5 时间区间查询
表结构如下
需求
查询在2025年内
投递简历的每个岗位,每一个月内
收到简历的数量,并且按先按月份降序
排序,再按简历数目降序
排序。
SQL语句
select job, date_format(date,'%Y-%m') as mon, sum(num) as cnt
from resume_info
where date>'2025-01-01' and date<'2025-12-31'
group by mon,job
order by mon desc, cnt desc;
date_format()
函数使date
以一种特定的格式显示。
运行结果
6 平均值去掉最大最小值
表结构如下
需求
查找排除最大、最小salary
之后的当前(to_date = '9999-01-01' )
员工的平均工资avg_salary
。
SQL语句
select avg(salary) from salaries
where to_date = '9999-01-01'
and salary not in (select max(salary) from salaries where to_date = '9999-01-01')
and salary not in (select min(salary) from salaries where to_date = '9999-01-01');
需要注意的是,如下的SQL语句是会报错的。
select avg(salary) from salaries
where to_date = '9999-01-01'
and salary>min(salary)
and salary<max(salary);