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!

相关推荐
小小不董17 分钟前
Oracle RAC ‘Metrics Global Cache Blocks Lost‘告警解决处理
linux·服务器·数据库·oracle·dba
江沉晚呤时31 分钟前
深入解析 SqlSugar 与泛型封装:实现通用数据访问层
数据结构·数据库·oracle·排序算法·.netcore
木木子999938 分钟前
MySQL中的窗口函数
数据库·mysql
酷爱码39 分钟前
redis延时队列详细介绍
数据库·redis·缓存
duration~1 小时前
PostgreSQL初试
数据库·postgresql
小小不董2 小时前
Oracle OCP认证考试考点详解083系列04
数据库·oracle·dba
IT成长日记3 小时前
【Hive入门】Hive与Spark SQL深度集成:通过Spark ThriftServer高效查询Hive表
hive·sql·spark
Yvonne9784 小时前
MySQL进阶(二)
数据库·mysql
189228048614 小时前
NV203NV207SSD固态闪存NV208NV213
网络·数据库·oracle
张彦峰ZYF4 小时前
如何封装一个线程安全、可复用的 HBase 查询模板
数据库·安全·hbase