【SQL】温度比较

发布于:2024-10-15 ⋅ 阅读:(79) ⋅ 点赞:(0)

目录

语法

需求

示例

分析

代码


语法

DATEDIFF(interval, start_date, end_date)

DATEDIFF是SQL中的一个函数,主要用于计算两个日期之间的差异。

  • interval:表示时间单位,可以是YEAR、MONTH、DAY、HOUR、MINUTE或SECOND等,具体取决于数据库管理系统的实现。
  • start_date或startdate:表示起始日期。
  • end_date或enddate:表示结束日期。

DATEDIFF函数返回两个日期之间指定时间单位的差值,结果是一个整数。如果start_date大于end_date,则结果通常为负值(具体取决于数据库管理系统的实现),例如

SELECT DATEDIFF(DAY, '2023-03-01', '2023-04-01') AS DaysDifference;

返回结果:28(表示从2023-03-01到2023-04-01之间有28天的差异)。

SELECT DATEDIFF(HOUR, '2023-01-01 12:00:00', '2023-01-01 14:30:00') AS HoursDifference;

返回结果:2.5(表示从2023-01-01 12:00:00到2023-01-01 14:30:00之间有2.5小时的差异)

SELECT DATEDIFF(MONTH, '2023-01-01', '2023-03-01') AS MonthsDifference;

返回结果:2(表示从2023-01-01到2023-03-01之间有2个月的差异)

需求

表: Weather

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

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

返回结果无顺序要求 。

示例

输入:
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

需要比较两个日前之间的温度,使用交叉连接 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 a cross join weather b 
     on timestampdiff(day, a.date, b.date) = -1
where a.temp > b.temp;