zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL中LAG()函数和LEAD()函数的使用

mysql 使用 函数 lag lead
2023-06-13 09:20:06 时间

从MySQL8之后才开始支持窗口函数

窗口函数 OVER ([PARTITION BY 用于分组的列 ] ORDER BY 用于排序的列 )

二、LAG()和LEAD()函数介绍 lag和lead分别是向前向后的意思 参数有三个。expression:列名;offset:偏移量;default_value:超出记录窗口的默认值(默认为null,可以设置为0)

三、数据准备(建表sql在最后)

在这里插入图片描述

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

我们还是先按照日期进行排序,然后找到当天比后一天温度高的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;

查询结果:

在这里插入图片描述

四、建表数据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()函数和LEAD()函数的使用的文章就介绍到这了,更多相关mysql LAG()和LEAD()函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


我想要获取技术服务或软件
服务范围:MySQL、ORACLE、SQLSERVER、MongoDB、PostgreSQL 、程序问题
服务方式:远程服务、电话支持、现场服务,沟通指定方式服务
技术标签:数据恢复、安装配置、数据迁移、集群容灾、异常处理、其它问题

本站部分文章参考或来源于网络,如有侵权请联系站长。
数据库远程运维 MySQL中LAG()函数和LEAD()函数的使用