赞
踩
lag()与lead函数是跟偏移量相关的两个分析函数
通过这两个函数可以在一次查询中取出同一字段的前N行的数据(lag)和后N行的数据(lead)作为独立的列,从而更方便地进行进行数据过滤,该操作可代替表的自联接,且效率更高
lag()/lead()
lag(col,n,DEFAULT)用于统计窗口内往上第n行值
第一个参数为列名
第二个参数为往上第n行(可选,默认为1)
第三个参数为默认值(当往上第n行为NULL时候,取默认值,如不指定,则为NULL)
lead()函数与lag()函数相反,用于统计窗口内往下第n行值
over()
表示lag()与lead()操作的数据都在over()的范围内,里面可以使用以下子句
partition by 语句(用于分组)
order by 语句()用于排序)
如:over(partition by a order by b) 表示以a字段进行分组,再以b字段进行排序,对数据进行查询
1、查找前一行或前N行的数据
2、比较相邻行的数据
3、查询n天内值是否连续增长的
有一张表kd_stock_history_info,里面有code(编码),date(日期),amount(销售额)三个字段,表数据如下:
通过hive如何获取到连续n天是增长状态的编码。例如查询2023-01-10这天的数据,也就是从2023-01-10这天往前数三天,看这三天的数据中amount是否连续增长,表中1001就不是,1002则符合。
- SELECT
- code,
- `date`,
- amount,
- LAG(amount) OVER (PARTITION by code ORDER BY `date`) AS prev_sales,
- amount - LAG(amount) OVER (PARTITION by code ORDER BY `date`) AS sales_diff
- FROM
- kd_stock_history_info
- where
- `date` BETWEEN DATE_SUB(TO_DATE('2023-01-10'), 2) AND TO_DATE('2023-01-10');
为了更美观一些,调整lag()函数默认值
- SELECT
- code,
- `date`,
- amount,
- LAG(amount,1,amount) OVER (PARTITION by code ORDER BY `date`) AS prev_sales,
- amount - LAG(amount,1,amount) OVER (PARTITION by code ORDER BY `date`) AS sales_diff
- FROM
- kd_stock_history_info
- where
- `date` BETWEEN DATE_SUB(TO_DATE('2023-01-10'), 2) AND TO_DATE('2023-01-10');
最终代码:
- SELECT code,min(sales_diff) min_sales_diff from (
- SELECT
- code,
- `date`,
- amount,
- LAG(amount,1,amount) OVER (PARTITION by code ORDER BY `date`) AS prev_sales,
- amount - LAG(amount,1,amount) OVER (PARTITION by code ORDER BY `date`) AS sales_diff
- FROM
- kd_stock_history_info
- where
- `date` BETWEEN DATE_SUB(TO_DATE('2023-01-10'), 2) AND TO_DATE('2023-01-10')
- ) a
- group by code
- having min_sales_diff >= 0;
更多资料:
Hive Lag函数用法介绍_笔记大全_设计学院 (python100.com)
Hive窗口函数04-LAG、LEAD、FIRST_VALUE、LAST_VALUE-腾讯云开发者社区-腾讯云 (tencent.com)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。