【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;
相关推荐
Lxinccode2 小时前
Java查询数据库表信息导出Word-获取数据库实现[1]:KingbaseES
java·数据库·word·获取数据库信息·获取kingbasees信息
豆沙沙包?3 小时前
5.学习笔记-SpringMVC(P61-P70)
数据库·笔记·学习
朴拙数科5 小时前
MongoDB Atlas与MongoDB连接MCP服务器的区别解析
服务器·数据库·mongodb
柏油5 小时前
MySQL InnoDB 行锁
数据库·后端·mysql
A-Kamen5 小时前
MySQL 存储引擎对比:InnoDB vs MyISAM vs Memory
数据库·mysql·spark
极限实验室6 小时前
【Workshop 第一期 - 北京站】搜索服务统一治理(跨引擎多个集群监控管理、流量管控、服务编排)
数据库
鹏翼丶6 小时前
搭建动态SQL取数
数据库·sql·动态sql
辰哥单片机设计6 小时前
PH传感器详解(STM32)
数据库·mongodb
JavaAlpha6 小时前
面试题:Redis 一次性获取大量Key的风险及优化方案
数据库·redis·bootstrap
尽兴-6 小时前
Mac「brew」快速安装Redis
数据库·redis·macos·brew