【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;
相关推荐
q_191328469524 分钟前
基于SpringBoot+Vue.js的高校竞赛活动信息平台
vue.js·spring boot·后端·mysql·程序员·计算机毕业设计
semantist@语校30 分钟前
第五十八篇|从城市节律到制度密度:近畿日本语学院的数据建模与关西语校结构工程
大数据·服务器·数据库·人工智能·百度·ai·知识图谱
小宇的天下1 小时前
Calibre 工具的几何处理基础(11-1)
数据库·oracle
小韩博1 小时前
小迪笔记45课之-PHP应用&SQL二次注入&堆叠执行&DNS带外&功能点&黑白盒条件
笔记·sql·网络安全·php
hgz07101 小时前
慢SQL分析与优化实战
mysql
talenteddriver2 小时前
mysql: MySQL索引基础概念
数据库·mysql
蜂蜜黄油呀土豆2 小时前
MySQL 事务原理深度解析:从 ACID 到并发控制机制
mysql·mvcc·并发控制·数据库事务·acid
king_harry2 小时前
PostgreSQL WAL 原理剖析、日志堆积治理与流复制监控
数据库·postgresql·wal·流复制
默默前行的虫虫2 小时前
nicegui网页多用户数据隔离总结
数据库·sql
特立独行的猫a2 小时前
PostgreSQL客户端工具介绍:从性能测试到跨平台管理
数据库·docker·postgresql·客户端·pgadmin4