• SQL中的LAG函数与LEAD函数用法


    LAG:函数用于获取结果集中当前行之前的某一行的值

    1. LAG (scalar_expression [,offset] [,default]) OVER ([partition_by_clause ] order_by_clause )
    2. -----汉字解释
    3. LAG (字段 [,偏移量默认为1] [,如果没有值时候默认值]) OVER ( [ partition_by 字段 ] order_by 字段 )

    Lead:函数用于获取结果集中当前行之后的某一行的值

    1. LEAD (scalar_expression [,offset] [,default]) OVER ([partition_by_clause ] order_by_clause )
    2. -----汉字解释
    3. LEAD (字段 [,偏移量默认为1] [,如果没有值时候默认值]) OVER ( [ partition_by 字段 ] order_by 字段 )

    原数据

    1. select * from tmp
    2. order_id | order_date | customer_name | price | product_id | order_status
    3. ----------+------------+---------------+----------+------------+--------------
    4. 1 | 2020-07-28 | Jark | 50.50000 | 102 | f
    5. 2 | 2020-07-29 | Sally | 15.00000 | 105 | f
    6. 3 | 2020-07-30 | Edward | 25.25000 | 106 | f
    7. 4 | 2020-07-31 | Edward | 25.25000 | 106 | f
    1. select *,lag(order_id,1,99) over(partition by order_status order by order_Date) from tmp;
    2. order_id | order_date | customer_name | price | product_id | order_status | lag
    3. ----------+------------+---------------+----------+------------+--------------+-----
    4. 1 | 2020-07-28 | Jark | 50.50000 | 102 | f | 99
    5. 2 | 2020-07-29 | Sally | 15.00000 | 105 | f | 1
    6. 3 | 2020-07-30 | Edward | 25.25000 | 106 | f | 2
    7. 4 | 2020-07-31 | Edward | 25.25000 | 106 | f | 3
    8. ------------------------------------------------------------------------------------
    9. select *,lead(order_id,1,99) over(partition by order_status order by order_Date) from tmp;
    10. order_id | order_date | customer_name | price | product_id | order_status | lead
    11. ----------+------------+---------------+----------+------------+--------------+------
    12. 1 | 2020-07-28 | Jark | 50.50000 | 102 | f | 2
    13. 2 | 2020-07-29 | Sally | 15.00000 | 105 | f | 3
    14. 3 | 2020-07-30 | Edward | 25.25000 | 106 | f | 4
    15. 4 | 2020-07-31 | Edward | 25.25000 | 106 | f | 99

     lag和lead的用法中order by的顺序都是asc的,也就是这两个可以使用降序排序的写法就能等于另一个了,

    lag()over(order by 字段 desc)=lead over(order by 字段)

    lead()over (order by 字段 desc)=lag over(order by 字段)

  • 相关阅读:
    编程语言未来发展趋势之我见
    【leetcode刷题之路】面试经典150题(6)——图+图的广度优先搜索+字典树+回溯
    记一次线程爆满导致服务器崩溃的问题排查
    面试:HashMap
    python3GUI--仿做一个网易云音乐(第三弹v2.0)By:PyQt5(附下载地址)
    论语第一篇-学而
    实现文件管理
    FSOD论文阅读 - 基于卷积和注意力机制的小样本目标检测
    Jasper狂飙:AIGC现象级应用的增长秘笈
    Win7系统如何在线进行重装?在线一键重装Win7方法
  • 原文地址:https://blog.csdn.net/yyf960126/article/details/128412568