gpt4 book ai didi

mysql - 编写 SQL 查询以查找接近 min() 值的行

转载 作者:行者123 更新时间:2023-11-29 02:27:45 25 4
gpt4 key购买 nike

我有大约 5000 行数据如下:

id    date        temperature     room --------------------------------------0    2013-07-15   76              A1    2013-08-15   72              A2    2013-09-15   74              B3    2013-02-15   71              B4    2013-03-15   72              B5    2013-04-15   70              A.........5000 2013-08-01   68              A

我可以使用下面的查询来查找每个房间的最低温度。

select room, min(temperature) from table_record group by room.

现在,我需要找到接近每个房间最低温度的所有行。我尝试在同一张表上使用“加入”,但无法运行。

select t1.room, min(t1.temperature) from table_record t1   join on table_record t2 on             t2.room = t1.room and             t2.temperature * 0.95 (less_or_equal) min(t1.temperature)  group by room

最佳答案

您需要分两步完成此操作。

SELECT
*
FROM
(
SELECT room, MIN(temperature) AS min_temp FROM TABLE_RECORD GROUP BY room
)
AS ROOM_TEMP
INNER JOIN
TABLE_RECORD
ON TABLE_RECORD.room = ROOM_TEMP.room
AND TABLE_RECORD.temperature <= ROOM_TEMP.min_temp / 0.95

前提是你在(room, temperature)上有索引这应该很快。

另外,请注意我使用 x <= y / 0.95而不是 x * 0.95 <= y .这是为了加快查找速度(操作一次搜索条件,而不是每一行的搜索字段)

关于mysql - 编写 SQL 查询以查找接近 min() 值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18497576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com