-- lag 和 lead 一样
lag(value_expr, [offset], [default]) over([partition by ..] order by ..)
(1) value_expr: 字段名
(2) offset: 偏移量 -> N 默认 1
(3) default: 字段值超出偏移量时的默认值,默认为 null
实例1:获取当前记录的 id 、上一条记录的 id 以及 下一条记录的 id
WITH t_test AS (
SELECT 1 ID, 'a' NAME, '男' sex FROM dual UNION ALL
SELECT 2 ID, 'b' NAME, '女' sex FROM dual UNION ALL
SELECT 3 ID, 'c' NAME, '女' sex FROM dual UNION ALL
SELECT 4 ID, 'd' NAME, '女' sex FROM dual UNION ALL
SELECT 5 ID, 'e' NAME, '男' sex FROM dual
)
SELECT t.id,
LAG(t.id, 1, NULL) OVER(ORDER BY t.id) previous_id,
LEAD(t.id, 1, NULL) OVER(ORDER BY t.id) next_id,
t.name,
t.sex
FROM t_test t;
实例2:获取 “性别” 相同的,当前记录的 id 、上一条记录的 id 以及 下一条记录的 id
WITH t_test AS (
SELECT 1 ID, 'a' NAME, '男' sex FROM dual UNION ALL
SELECT 2 ID, 'b' NAME, '女' sex FROM dual UNION ALL
SELECT 3 ID, 'c' NAME, '女' sex FROM dual UNION ALL
SELECT 4 ID, 'd' NAME, '女' sex FROM dual UNION ALL
SELECT 5 ID, 'e' NAME, '男' sex FROM dual
)
SELECT t.id,
LAG(t.id, 1, NULL) OVER(PARTITION BY t.sex ORDER BY t.id) previous_id,
LEAD(t.id, 1, NULL) OVER(PARTITION BY t.sex ORDER BY t.id) next_id,
t.name,
t.sex
FROM t_test t;
实例3:获取 “性别” 相同的,当前记录的 id 和 下一条记录的 id 相差 2 及以上的记录
WITH t_test AS (
SELECT 1 ID, 'a' NAME, '男' sex FROM dual UNION ALL
SELECT 2 ID, 'b' NAME, '女' sex FROM dual UNION ALL
SELECT 3 ID, 'c' NAME, '女' sex FROM dual UNION ALL
SELECT 4 ID, 'd' NAME, '女' sex FROM dual UNION ALL
SELECT 5 ID, 'e' NAME, '男' sex FROM dual
)
SELECT tt.*
FROM (SELECT t.id,
lead(t.id, 1, NULL) over(PARTITION BY t.sex ORDER BY t.id) next_id,
t.name,
t.sex
FROM t_test t) tt
WHERE tt.next_id >= tt.id + 2;