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;

相关推荐
RestCloud15 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud15 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence17 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug2 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom2 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试