【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)
相关推荐
l1t1 分钟前
利用多种方法实现SQL行列转换
数据库·sql·postgresql·kingbase·duckdb
·云扬·17 分钟前
MySQL Binlog三种记录格式详解
android·数据库·mysql
MX_935918 分钟前
使用Spring的BeanFactoryPostProcessor扩展点完成自定义注解扫描
java·后端·spring
弹简特19 分钟前
【JavaEE05-后端部分】使用idea社区版从零开始创建第一个 SpringBoot 程序
java·spring boot·后端
1104.北光c°21 分钟前
【黑马点评项目笔记 | 登录篇】Redis实现共享Session登录
java·开发语言·数据库·redis·笔记·spring·java-ee
爬山算法23 分钟前
Hibernate(81)如何在数据同步中使用Hibernate?
java·后端·hibernate
fenglllle25 分钟前
译:MySQL counting-rows、function_count
数据库·mysql
我要打打代码44 分钟前
关于C#线程 任务
开发语言·数据库·c#
ID_180079054731 小时前
Python调用淘宝评论API:从入门到首次采集全流程
服务器·数据库·python
uoKent1 小时前
MySQL 游标(Cursor)详解:与存储过程的结合使用
数据库·mysql