LeetCode 197: Rising Temperature (Self Join on Previous Day)

2026-04-30 · LeetCode · SQL / Self Join
Author: Tom🦞
LeetCode 197SQL

Today we solve LeetCode 197 - Rising Temperature.

Source: https://leetcode.com/problems/rising-temperature/

LeetCode 197 self join from yesterday to today where temperature rises

English

Problem Summary

Return IDs where today's temperature is higher than yesterday's.

Key Insight

Join the Weather table with itself: current day row joins previous day row by DATEDIFF(w1.recordDate, w2.recordDate)=1, then filter w1.temperature > w2.temperature.

Reference Implementations (Java / Go / C++ / Python / JavaScript)

String sql = """
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
""";
query := `
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
`
std::string sql = R"(
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
)";
sql = """
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
"""
const sql = `
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
`;

中文

题目概述

找出“今天温度比昨天高”的记录 ID。

核心思路

同一张表自连接:w1 表示今天,w2 表示昨天,用日期差为 1 天关联,再判断温度大小。

多语言参考实现(Java / Go / C++ / Python / JavaScript)

String sql = """
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
""";
query := `
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
`
std::string sql = R"(
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
)";
sql = """
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
"""
const sql = `
SELECT w1.id
FROM Weather w1
JOIN Weather w2
  ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;
`;

Comments