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!

相关推荐
手把手入门1 小时前
★CentOS:MySQL数据备份
数据库·mysql·adb
喂完待续1 小时前
【Tech Arch】Hive技术解析:大数据仓库的SQL桥梁
大数据·数据仓库·hive·hadoop·sql·apache
SelectDB2 小时前
5000+ 中大型企业首选的 Doris,在稳定性的提升上究竟花了多大的功夫?
大数据·数据库·apache
路多辛2 小时前
Golang database/sql 包深度解析(二):连接池实现原理
数据库·sql·golang
SimonKing2 小时前
Mybatis批量插入,形式不同性能也不同
数据库·后端·程序员
杰克尼3 小时前
MYSQL-175. 组合两个表
数据库·mysql
DemonAvenger3 小时前
MySQL索引原理深度解析与优化策略实战
数据库·mysql·性能优化
189228048614 小时前
NY270NY273美光固态闪存NY277NY287
服务器·网络·数据库·科技·性能优化
javachen__6 小时前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
星霜笔记7 小时前
Docker 部署 MariaDB+phpMyAdmin+Nextcloud 完整教程
运维·数据库·docker·容器·mariadb