SQL笔记-2024/01/31

cross join

两个表的笛卡尔积

例如:

select s.name student_name,s.age student_age,s.class_id class_id,c.name class_name

from student s

cross join class c;

子查询

select s.name name,s.score score,s.class_id class_id

from student s

where s.class_id in (select distinct c.id from class c);

子查询 - exists

select s.name,s.age,s.class_id

from student s

where 1=1

and not exists (select 1 from class c where c.id = s.class_id);

组合查询

union 不保留重复行

union all 保留重复行

select s.name,s.age,s.score,s.class_id

from student s

union all

select sn.name,sn.age,sn.score,sn.class_id

from student_new sn;

开窗函数 - sum over

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,AVG(score) over (partition by class_id) as class_avg_score

from student s;

开窗函数 - sum over order by

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,SUM(score) over (partition by class_id order by score asc) as class_sum_score

from student s;

开窗函数 - rank

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,RANK() over (partition by class_id order by score desc) as ranking

from student s;

查询进阶 - 开窗函数 - row_number

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,ROW_NUMBER() over (partition by class_id order by score desc) as row_number

from student s;

开窗函数 - lag / lead

select s.id id,s.name name,s.age age,s.score score,s.class_id class_id,

LAG(name,1,null) over (partition by class_id order by score desc) as prev_name,

LEAD(name,1,null) over (partition by class_id order by score desc) as next_name

from student s;

相关推荐
2601_9495936515 分钟前
深入解析CANN-acl应用层接口:构建高效的AI应用开发框架
数据库·人工智能
javachen__16 分钟前
mysql新老项目版本选择
数据库·mysql
Dxy123931021634 分钟前
MySQL如何高效查询表数据量:从基础到进阶的优化指南
数据库·mysql
Dying.Light37 分钟前
MySQL相关问题
数据库·mysql
蜡笔小炘1 小时前
LVS -- 利用防火墙标签(FireWall Mark)解决轮询错误
服务器·数据库·lvs
韩立学长1 小时前
基于Springboot泉州旅游攻略平台d5h5zz02(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游
Re.不晚2 小时前
MySQL进阶之战——索引、事务与锁、高可用架构的三重奏
数据库·mysql·架构
老邓计算机毕设2 小时前
SSM智慧社区信息化服务平台4v5hv(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架·智慧社区、·信息化平台
麦聪聊数据2 小时前
为何通用堡垒机无法在数据库运维中实现精准风控?
数据库·sql·安全·低代码·架构
2301_790300962 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python