202553-sql

目录

[一、196. 删除重复的电子邮箱 - 力扣(LeetCode)](#一、196. 删除重复的电子邮箱 - 力扣(LeetCode))

[二、602. 好友申请 II :谁有最多的好友 - 力扣(LeetCode)](#二、602. 好友申请 II :谁有最多的好友 - 力扣(LeetCode))

[三、176. 第二高的薪水 - 力扣(LeetCode)](#三、176. 第二高的薪水 - 力扣(LeetCode))


一、196. 删除重复的电子邮箱 - 力扣(LeetCode)

题意就是删除删除重复的邮箱

很容易可以想到 delete from person where id in (一坨)

绕了个弯子 让你写删除语句本质还是写查询语句

  1. 第一层查询使用窗口函数 分组加排序

    sql 复制代码
    select *,
    row_number() over(partition by email order by id asc) as 'rank' 
    from Person
  2. 可以显然得出 临时表中rank >1 的都是重复的,嵌套一层查id出来

    sql 复制代码
     select id from (
            select *,
                    row_number() over(partition by email order by id asc) as 'rank' from Person
        ) temp  where temp.rank = 1
  3. 执行删除语句

    sql 复制代码
    delete from Person where id not in (
        select id from (
            select *,row_number() over(partition by email order by id asc) as 'rank' from Person
        ) temp  where temp.rank = 1
    )

二、602. 好友申请 II :谁有最多的好友 - 力扣(LeetCode)

sql 复制代码
with t1 as(
    select requester_id as 'id' from RequestAccepted
    union all
    select accepter_id  as 'id' from RequestAccepted
),
t2 as(
    select id,count(id) over(partition by id rows between unbounded preceding and unbounded following) as 'num'
    from t1
),
t3 as(
    select *,dense_rank() over(partition by null order by num desc) as 'rank'
    from t2
)
select id,num 
from t3 
where t3.rank = 1
limit 1

理解就是加好友是相互的!!!!!!!!

把两列数据并成一列 然后窗口函数分组排序

三、176. 第二高的薪水 - 力扣(LeetCode)

也是窗口函数分组排序 但是这个题就比较麻烦 需要考虑空结果集输出null

sql 复制代码
select ifnull((
    with t1 as(
        select *,dense_rank() over(partition by null order by salary desc) as 'rank'
        from Employee
    ),
    t2 as(
        select distinct salary as 'SecondHighestSalary' 
        from t1
        where t1.rank = 2
    )
    select SecondHighestSalary from t2
),null) as 'SecondHighestSalary'

结束三道sql!

相关推荐
Raymond运维14 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉14 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger2 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql