MYSQL数据比较

kxeu7u2r  于 2023-06-28  发布在  Mysql
关注(0)|答案(2)|浏览(116)

对比一下今天和昨天的温度。如果今天的比我想要的要高,返回该行的id。
表格有3列:idRecordDatetemperature
代码适用于小数据集,但在查看1400的数据集时,失败率为1%。

SELECT DISTINCT
    id

FROM
    (
        SELECT DISTINCT
            id,
            recordDate, 
            recordDate - LAG(recordDate, 1) OVER (ORDER BY recordDate) AS diff, 
            temperature - LAG(temperature, 1) OVER (ORDER BY recordDate) AS dif

        FROM
            Weather
    ) AS t

WHERE
    dif > 0
    AND
    diff = 1

ORDER BY
    id ASC;

我希望这将按recordDate对数据进行排序。
要捕获ID,必须满足2个条件
1.今天的温度比昨天高(dif > 0
1.而昨天实际上就是昨天-行之间只能有1天的差异(diff = 1
让我知道你会如何改善这一点!已经磨了一段时间,可以使用的帮助。我觉得有更简单的方法。

1zmg4dgp

1zmg4dgp1#

SELECT DISTINCT id
FROM (
    SELECT id,
           recordDate,
           temperature - LAG(temperature) OVER (ORDER BY recordDate) AS dif
    FROM Weather
) AS t
WHERE dif > 0
  AND EXTRACT(DAY FROM (recordDate - LAG(recordDate) OVER (ORDER BY recordDate))) = 1
ORDER BY id ASC;
6fe3ivhb

6fe3ivhb2#

我不知道性能如何,但你觉得这个怎么样?

SELECT w2.id from Weather w1 join Weather w2 
ON w2.temperature>w1.temperature 
AND date(w1.recordDate) = date(date_add(w2.recordDate, interval 1 day))

相关问题