常用窗口函数

1、ROW_NUMBER

  • 命令格式
    row_number() over(partition by [col1, col2…]
    order by [col1[asc|desc], col2[asc|desc]…])
  • 命令说明

    该函数用于计算行号,从1开始。

  • 参数说明
    • partition by [col1, col2..]:指定开窗口的列。
    • order by col1[asc|desc], col2[asc|desc]:指定结果返回时的排序的值。
  • 返回值说明

    返回BIGINT类型。

  • 用于去重

  

SELECT *
FROM (
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY t.去重字段 ORDER BY t.去重字段 DESC) AS rn
    FROM xxx t
) p
WHERE p.rn = 1;

2、LAG

  • 命令格式
    lag(expr,Bigint offset, default) over(partition by [col1, col2…]
    [order by [col1[asc|desc], col2[asc|desc]…]])
  • 命令说明

    按偏移量取当前行之前第几行的值。如果当前行号为rn,则取行号为rn-offset的值。

   LAG()窗口函数返回分区中当前行之前行(可以指定第几行)的值。 如果没有行,则返回null。

  • 参数说明
    • expr:任意类型。
    • offset:BIGINT类型常量。输入值为STRING、DOUBLE到BIGINT的隐式转换,offset>0。
    • default:当offset指定的范围越界时的缺省值,常量,默认值为NULL。
    • partition by [col1, col2..]:指定开窗口的列。
    • order by col1[asc|desc], col2[asc|desc]:指定返回结果的排序方式。
  • 返回值说明

    返回值类型同expr类型。

3、LEAD

  • 命令格式
    lead(expr,Bigint offset, default) over(partition by [col1, col2…]
    [order by [col1[asc|desc], col2[asc|desc]…]])
  • 命令说明

    按偏移量取当前行之后第几行的值。如果当前行号为rn,则取行号为rn+offset的值。

   LEAD()窗口函数返回分区中当前行后面行(可以指定第几行)的值。 如果没有行,则返回null。

  • 参数说明
    • expr:任意类型。
    • offset:可选,BIGINT类型常量。输入值为STRING、DECIMAL、DOUBLE到BIGINT的隐式转换,offset>0。
    • default:可选,当offset指定的范围越界时的缺省值,常量。
    • partition by [col1, col2..]:指定开窗口的列。
    • order by col1[asc|desc], col2[asc|desc]:指定返回结果的排序方式。
  • 返回值说明

    返回值类型同expr类型。

猜你喜欢

转载自www.cnblogs.com/suheng01/p/12354965.html