MySQL中LAG()函數(shù)和LEAD()函數(shù)的使用
一、窗口函數(shù)的基本用法
從MySQL8之后才開始支持窗口函數(shù)
<窗口函數(shù)> OVER ([PARTITION BY <用于分組的列>] ORDER BY <用于排序的列>)
二、LAG()和LEAD()函數(shù)介紹
- lag和lead分別是向前向后的意思
- 參數(shù)有三個。expression:列名;offset:偏移量;default_value:超出記錄窗口的默認值(默認為null,可以設置為0)
三、數(shù)據(jù)準備(建表sql在最后)
1、LAG()函數(shù):統(tǒng)計與前一天相比溫度更高的日期Id
我們先按照日期進行排序,然后找到當天比前一天溫度高的id;使用lag()函數(shù),將溫度向后推一天。
select id, date, temperature, LAG(temperature, 1, 0) OVER (order by date) as temp FROM weather
查詢結果:
然后將temperature大于temp 并且temp不等于0的數(shù)據(jù)挑選出來
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()函數(shù):統(tǒng)計與后一天相比溫度更高的日期Id
我們還是先按照日期進行排序,然后找到當天比后一天溫度高的id;使用lead()函數(shù),將溫度向后推一天。
select id, date, temperature, LEAD(temperature, 1, 0) OVER (order by date) as temp FROM weather
查詢結果:
然后將temperature大于temp 并且temp不等于0的數(shù)據(jù)挑選出來
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;
查詢結果:
四、建表數(shù)據(jù)sql
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()函數(shù)和LEAD()函數(shù)的使用的文章就介紹到這了,更多相關mysql LAG()和LEAD()函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MySQL查看和優(yōu)化數(shù)據(jù)庫實例詳細信息的命令
本文詳細介紹了如何查看?MySQL?數(shù)據(jù)庫實例的信息,包括基本信息、配置參數(shù)、運行進程和性能監(jiān)控等方面,通過多個代碼示例,讀者可以掌握查看和管理數(shù)據(jù)庫實例的具體操作,這些方法和工具對于數(shù)據(jù)庫管理和維護非常重要,可以幫助我們確保數(shù)據(jù)庫的健康運行2024-05-05MySQL錯誤代碼1862 your password has expired的解決方法
這篇文章主要為大家詳細介紹了MySQL錯誤代碼1862 your password has expired的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08linux下mysql5.7.17最新穩(wěn)定版本安裝教程
這篇文章主要為大家詳細介紹了linux上mysql5.7.17最新穩(wěn)定版本安裝教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02