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!

相关推荐
DarkAthena5 分钟前
【GaussDB】从 sqlplus 到 gsql:Shell 中执行 SQL 文件方案的迁移与改造
数据库·sql·oracle·gaussdb
Wpa.wk8 分钟前
接口自动化 - 了解接口自动化框架RESTAssured (Java版)
java·数据库·自动化
二等饼干~za89866812 分钟前
GEO优化---关键词搜索排名源码开发思路分享
大数据·前端·网络·数据库·django
程序员柒叔15 分钟前
Dify 集成-向量数据库
数据库·milvus·向量数据库·工作流·dify·向量库
月明长歌15 分钟前
MySQL 视图:把复杂查询封装成表,并且还能控权限、做解耦
数据库·mysql
l1t16 分钟前
postgresql 18版bytea 类型转换的改进
数据库·postgresql
小蒜学长20 分钟前
python餐厅点餐系统(代码+数据库+LW)
数据库·spring boot·后端·python
岳麓丹枫00123 分钟前
PostgreSQL 中 create database 中的注意事项
数据库·postgresql
梦想画家23 分钟前
告别关键词!PostgreSQL+pgvector 玩转语义和图像检索
数据库·postgresql
爱潜水的小L1 小时前
自学嵌入式day41,数据库
jvm·数据库