【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)
相关推荐
坚定信念,勇往无前3 小时前
mongodb的日志分割
数据库·mongodb
学长毕业设计6 小时前
基于SpringBoot的公益基金管理系统(源码+文档+讲解视频)
java·spring boot·后端
东小西6 小时前
【SAA实战】第 3 篇 · 工具调用全攻略:把业务能力交给 Agent 自己调度
java·后端·spring
东小西6 小时前
【SAA实战】第 4 篇 · Agent 短期记忆:saver 让 Agent 跨轮记得住(threadId 隔离)
java·后端·spring
圣保罗的大教堂6 小时前
leetcode 1406. 石子游戏 III 困难
leetcode
oradh6 小时前
Oracle TX 锁 Mode 4(Share)问题排查总结
数据库·oracle·tx 锁 mode 4·oracle tx 锁
2601_962065257 小时前
[MySQL] SQL优化之性能分析
java·sql·mysql
yi.Ist7 小时前
数据定义语言-DDL操作
数据库·学习·mysql·oracle·大海豚
阿kun要赚马内7 小时前
MySQL 索引基础
后端·mysql
码事漫谈7 小时前
我啥都能做,却不知道做什么了
后端