【SQL】温度比较

目录

题目

分析

代码


题目

表: Weather

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是该表具有唯一值的列。
没有具有相同 recordDate 的不同行。
该表包含特定日期的温度信息

编写解决方案,找出与之前(昨天的)日期相比温度更高的所有日期的 id

返回结果无顺序要求 。

示例 1:

复制代码
输入:
Weather 表:
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+
输出:
+----+
| id |
+----+
| 2  |
| 4  |
+----+
解释:
2015-01-02 的温度比前一天高(10 -> 25)
2015-01-04 的温度比前一天高(20 -> 30)

分析

找出与之前(昨天的)日期相比温度更高的所有日期的 id

比较,使用交叉连接corss join

简洁写法 from Weather w1 , Weather w2

目标id, select w1.id

日期比较,前一日,datediff(w1.recordDate,w2.recordDate) = 1

温度比较,w1.temperature > w2.temperature

同时满足,and

代码

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

思考代码

复制代码
select a.ID, a.date
from weather as a cross join weather as b 
     on timestampdiff(day, a.date, b.date) = -1
where a.temp > b.temp;
相关推荐
稻草人想看远方1 分钟前
关系型数据库和非关系型数据库
数据库
考虑考虑2 分钟前
Postgerssql格式化时间
数据库·后端·postgresql
依稀i1235 分钟前
Spring Boot + MySQL 创建超级管理员
spring boot·mysql
千里码aicood11 分钟前
【springboot+vue】党员党建活动管理平台(源码+文档+调试+基础修改+答疑)
java·数据库·spring boot
Chan1614 分钟前
【智能协同云图库】基于统一接口架构构建多维度分析功能、结合 ECharts 可视化与权限校验实现用户 / 管理员图库统计、通过 SQL 优化与流式处理提升数据
java·spring boot·后端·sql·spring·intellij-idea·echarts
TDengine (老段)31 分钟前
TDengine 选择函数 Max() 用户手册
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
驾驭人生40 分钟前
Asp .Net Core 系列:Asp .Net Core 集成 Hangfire+MySQL
数据库·mysql·.netcore
float_六七1 小时前
预编译SQL:安全与性能的双重保障
sql·安全·oracle
xhbh6661 小时前
不止是DELETE:MySQL多表关联删除的JOIN语法实战详解
数据库·mysql·程序员·mysql删除语句