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;

相关推荐
这个DBA有点耶1 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G1 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备1 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远1 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
漂着的圆木1 天前
Agent 功能参与度:Copilot 怎么算
sql·数据分析·agent·githubcopilot·度量
2601_962218611 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法
张洛闻Eren1 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github
于平安1 天前
MySQL-触发器
数据库·mysql
白远山1 天前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
Omics Pro1 天前
斯坦福Nature+Science|广义虚拟细胞基础大模型
数据库·人工智能·算法·机器学习·自然语言处理