KingbaseES lag 和 lead 函数
1.简介
lag与lead函数是跟偏移量相关的两个分析函数,通过这两个函数可以在一次查询中取出同一字段的前N行的数据(lag)和后N行的数据(lead)作为独立的列,从而更方便地进行进行数据过滤。
2.语法
LEAD/lag (expression [, offset [, default_value]])
OVER (
[PARTITION BY partition_expression, ... ]
ORDER BY sort_expression [ASC | DESC], ...
)
over()表示 lag()与lead()操作的数据都在over()的范围内,他里面可以使用partition by 语句(用于分组) order by 语句(用于排序)。partition by a order by b表示以a字段进行分组,再以b字段进行排序,对数据进行查询。
3.示例
示例数据:
test=# select * from sales;
year | group_id | amount
------+----------+---------
2021 | 1 | 1474.00
2021 | 2 | 1787.00
2021 | 3 | 1760.00
2019 | 1 | 1915.00
2019 | 2 | 1911.00
2019 | 3 | 1118.00
2020 | 1 | 1646.00
2020 | 2 | 1975.00
2020 | 3 | 1516.00
(9 行记录)
查询当年和下一年的销售额:
test=# WITH cte AS (
test(# SELECT
test(# year,
test(# SUM(amount) amount
test(# FROM sales
test(# GROUP BY year
test(# ORDER BY year
test(# )
test-# SELECT
test-# year,
test-# amount,
test-# LEAD(amount, 1) OVER (ORDER BY year) next_year_sales
test-# from cte;
year | amount | next_year_sales
------+---------+-----------------
2019 | 4944.00 | 5137.00
2020 | 5137.00 | 5021.00
2021 | 5021.00 |
(3 行记录)
每个产品组的当年销售额与下一年的销售额进行比较,没有销售额的默认为0:
test=# select year, amount, group_id,
test-# LEAD(amount, 1,0::numeric) OVER (PARTITION BY group_id ORDER BY year) next_year_sales
test-# FROM sales;
year | amount | group_id | next_year_sales
------+---------+----------+-----------------
2019 | 1915.00 | 1 | 1646.00
2020 | 1646.00 | 1 | 1474.00
2021 | 1474.00 | 1 | 0
2019 | 1911.00 | 2 | 1975.00
2020 | 1975.00 | 2 | 1787.00
2021 | 1787.00 | 2 | 0
2019 | 1118.00 | 3 | 1516.00
2020 | 1516.00 | 3 | 1760.00
2021 | 1760.00 | 3 | 0
lag函数用法与lead一致,这里就不再演示了。