從MySQL8之後才開始支援視窗函數
<窗口函数> OVER ([PARTITION BY <用于分组的列>] ORDER BY <用于排序的列>)
lag和lead分別是向前向後的意思
參數有三個。 expression:列名;offset:偏移量;default_value:超出記錄視窗的預設值(預設值null,可以設定為0)
1、LAG()函數:統計與前一天相比溫度更高的日期Id
我們先按照日期排序,然後找到當天比前一天溫度高的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;
結果如下:
2、LEAD()函數:統計與後一天相比溫度更高的日期Id
首先,我們對日期進行排序,接著使用lead ()函數將溫度向後推一天,找出當天比後一天溫度高的id。
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;
以上是MySQL中LAG()函式和LEAD()函式如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!