【SQL题解】力扣高频 SQL 50题|DAY4

SQL刷题记录

明天考数据库概论,今天晚上刷几道常考的连接题巩固一下

以下皆出自力扣高频SQL50题

文章目录

25.12.23

1378

1378. 使用唯一标识码替换员工ID

"展示每位用户的 唯一标识码(unique ID );如果某位员工没有唯一标识码,使用 null 填充"由此可知:

需要用到左外连接,左表是Employees

sql 复制代码
select unique_id,name 
from Employees a 
left join EmployeeUNI b 
on a.id = b.id;

1068

1068. 产品销售分析 I

简答的内连接

sql 复制代码
select p.product_name,s.year,s.price 
from Sales s 
join Product p 
on s.product_id = p.product_id; 

要给列名加前缀,不加可能会超时

方面 不加前缀(如 product_name 加前缀(如 p.product_name
正确性 可能出错(字段重名时) 安全明确
可读性 较差 清晰直观
执行效率 几乎无差别 几乎无差别(解析阶段略优)
工程规范 不推荐 强烈推荐

1581

1581. 进店却未进行过交易的顾客

  1. 先用左外连接,得到vistits表中每个customer_id对应的transaction_id,连接条件是两表的visit_id相等
  2. where transaction_id is null筛选出没有进行交易的
  3. 给筛选后的表用group by按照customer_id进行分组,并用count求出每组的个数
sql 复制代码
select customer_id,count(*) as count_no_trans
from Visits
left join Transactions
on Visits.visit_id = Transactions.visit_id
where transaction_id is null
group by customer_id;

197

197. 上升的温度

sql 复制代码
select w1.id as id 
from Weather w1,Weather w2 
where datediff(w1.recordDate,w2.recordDate) = 1 
and w1.Temperature > w2.Temperature;

from Weather w1,Weather w2

  • Weather 表和自己做笛卡尔积(隐式连接),生成所有可能的 (w1, w2) 记录对。
  • w1 代表"当前天",w2 代表"对比的另一天"

datediff(w1.recordDate,w2.recordDate) = 1筛选"相邻两天

DATEDIFF 是 SQL 中用于计算两个日期之间相差天数的函数

返回 date1 - date2 的整数天数差(只考虑日期部分,忽略时间)

w1.Temperature > w2.Temperature筛选温度升高

1661

1661. 每台机器的进程平均运行时间

sql 复制代码
select a1.machine_id as 'machine_id',
    ROUND(AVG(a2.timestamp - a1.timestamp) 
        ,3) as 'processing_time'
from Activity as a1
    join Activity as a2
    on a1.machine_id = a2.machine_id
        and a1.process_id = a2.process_id  
        and a1.activity_type = 'start' 
        and a2.activity_type = 'end'
group by a1.machine_id;

1 .FROM Activity AS a1 JOIN Activity AS a2自连接

  • Activity 表与自身连接,生成所有可能的记录对 (a1, a2)

2.连接条件

sql 复制代码
a1.machine_id = a2.machine_id
        and a1.process_id = a2.process_id  
        and a1.activity_type = 'start' 
        and a2.activity_type = 'end'

这四个条件确保:

  1. 同一台机器machine_id 相同)
  2. 同一个任务process_id 相同)
  3. a1 是开始事件activity_type = 'start'
  4. a2 是结束事件activity_type = 'end'

3.计算处理时间

a2.timestamp - a1.timestamp

4.按机器分组并求平均

sql 复制代码
GROUP BY a1.machine_id
  • 将同一台机器的所有任务处理时间聚合在一起。
  • AVG(...) 计算该机器所有任务的平均处理时间

5.保留三位小数

sql 复制代码
ROUND(AVG(...), 3)
相关推荐
Victor3563 分钟前
Hibernate(42)在Hibernate中如何实现分页?
后端
Victor3569 分钟前
Hibernate(41)Hibernate的延迟加载和急加载的区别是什么?
后端
陈天伟教授16 分钟前
关系数据库-07. 关系操作
数据库·达梦数据库·国产数据库
zzhongcy18 分钟前
复合索引 (item1, item2, item3 ) > (?, ?, ?) 不起作用,EXPLAIN 后type=ALL(全表扫描)
android·数据库
Elastic 中国社区官方博客22 分钟前
Elastic:DevRel 通讯 — 2026 年 1 月
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
猪猪拆迁队22 分钟前
2025年终总结-都在喊前端已死,这一年我的焦虑、挣扎与重组:AI 时代如何摆正自己的位置
前端·后端·ai编程
可观测性用观测云24 分钟前
AWS RDS 可观测性最佳实践
数据库
程序员小白条24 分钟前
面试 Java 基础八股文十问十答第八期
java·开发语言·数据库·spring·面试·职场和发展·毕设
ConardLi29 分钟前
SFT、RAG 调优效率翻倍!垂直领域大模型评估实战指南
前端·javascript·后端
汗流浃背了吧,老弟!1 小时前
向量数据库在RAG中的非必需场景及替代方案
数据库