从MySQL8之后才开始支持窗口函数
<窗口函数> OVER ([PARTITION BY <用于分组的列>] ORDER BY <用于排序的列>)
我们先按照日期进行排序,然后找到当天比前一天温度高的id;使用lag()函数,将温度向后推一天。
SELECT
id,
date,
temperature,
LAG( temperature, 1, 0 ) OVER ( ORDER BY date ) AS temp
FROM
weather;
查询结果:
然后将temperature大于temp 并且temp不等于0的数据挑选出来
SELECT
id
FROM
(SELECT id, date, temperature, LAG( temperature, 1, 0) OVER ( ORDER BY date ) AS temp FROM weather) tmp
WHERE
temperature > temp
AND temp != 0;
结果如下:
我们还是先按照日期进行排序,然后找到当天比后一天温度高的id;使用lead()函数,将温度向后推一天。
SELECT
id,
date,
temperature,
LEAD( temperature, 1, 0 ) OVER ( ORDER BY date ) AS temp
FROM
weather;
查询结果:
然后将temperature大于temp 并且temp不等于0的数据挑选出来
SELECT
id
FROM
( SELECT id, date, temperature, LEAD( temperature, 1, 0 ) OVER ( ORDER BY date ) AS temp FROM weather ) tmp
WHERE
temperature > temp
AND temp != 0;
查询结果:
DROP TABLE IF EXISTS `weather`;
CREATE TABLE `weather` (
`id` int(11) NOT NULL,
`date` date NULL DEFAULT NULL,
`temperature` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of weather
-- ----------------------------
INSERT INTO `weather` VALUES (1, '2022-08-01', 20);
INSERT INTO `weather` VALUES (2, '2022-08-02', 25);
INSERT INTO `weather` VALUES (3, '2022-08-03', 22);
INSERT INTO `weather` VALUES (4, '2022-08-04', 22);
INSERT INTO `weather` VALUES (5, '2022-08-05', 26);
INSERT INTO `weather` VALUES (6, '2022-08-06', 28);
INSERT INTO `weather` VALUES (7, '2022-08-07', 20);
SET FOREIGN_KEY_CHECKS = 1;