sql中的lag和lead函数是用于访问结果集中当前行前后数据的窗口函数,主要功能及用法如下:
一、函数定义
1、lag函数
获取当前行之前的第n行数据,语法:
lag(column, offset, default) over ([partition by] order by)
1、column
:目标列名
2、offset
:向前偏移的行数(默认1)
3、default
:无数据时的默认值(默认null)
2、lead函数 获取当前行之后的第n行数据,语法与lag类似(方向相反)
lead(column, offset, default) over ([partition by] order by)
1、column
:目标列名
2、offset
:向前偏移的行数(默认1)
3、default
:无数据时的默认值(默认null)
二、核心功能对比
函数 | 方向 | 典型应用场景 |
---|---|---|
lag | 向前 | 计算环比、填充缺失值、异常检测 |
lead | 向后 | 预测趋势、计算后续差值 |
三、使用示例
1、查询销售额及前一日数据:
select date, revenue, lag(revenue, 1, 0) over (order by date) as prev_revenue from sales
结果中prev_revenue
列显示前一日的销售额,首行默认值为0
2、按部门查询员工工资及前一位同事工资:
select deptno, empname, salary, lag(salary) over (partition by deptno order by hiredate) as prev_salary from emp
通过partition by
实现分组内偏移
3、计算每日销售额变化量:
select date, revenue - lag(revenue) over (order by date) as daily_change from sales
4、查询连续3天下单的customer_name,比如zhangsan在12.1、12.2号和12.3号连续3天下单过
补充:timestampdiff函数
timestampdiff(day, buy_date, next1_buy_date)
是 mysql 中用于计算两个日期之间天数差的函数,其功能解析如下:
函数结构:
1、参数1 day
:指定返回结果的时间单位(此处为天数)
2、参数2 buy_date
:起始日期(较早时间点)
3、参数3 next1_buy_date
:结束日期(较晚时间点)
4、返回值:next1_buy_date - buy_date
的天数差(整数,向下取整)
-- 写法一 select customer_name from ( select customer_name, buy_date, lag(buy_date,1) over(partition by customer_name order by buy_date) as next1_buy_date lead(buy_date,1) over(partition by customer_name order by buy_date) as next1_buy_date from order_table ) where timestampdiff(day,buy_date,next1_buy_date) = -1 and timestampdiff(day,buy_date,next2_buy_date) = 1;
-- 写法二 select customer_name from ( select customer_name, buy_date, lag(buy_date,1) over(partition by customer_name order by buy_date) as next1_buy_date lag(buy_date,2) over(partition by customer_name order by buy_date) as next1_buy_date from order_table ) where timestampdiff(day,buy_date,next1_buy_date) = -1 and timestampdiff(day,buy_date,next2_buy_date) = -2;
到此这篇关于sql中lag、lead函数功能及用法的文章就介绍到这了,更多相关sql lag lead函数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论