SQL知識之視窗函式

2021-10-23 06:10:35 字數 2564 閱讀 2471

3、排序視窗函式

4、切分視窗函式

5、偏移視窗函式

6、first_value() , last_value()

前言:視窗函式屬於sql的高階查詢功能,有些資料庫的低版本可能還不支援,如mysql5.7版本暫不支援,sql server是支援的。

1、視窗函式的簡單介紹

2、累計計算視窗函式

2.1 普通累計

# 以年為分組,按月份累加計算營業額

select

month

, amount,

sum(amount)

over

(partition

byyear

order

bymonth

)from trade

2.2 移動累計
rows

between

unbounded

preceding

andcurrent

row# 包括本行和之前的所有行

rows

between

3preceding

andcurrent

row# 包括本行以內和前三行

rows

between

current

rowand

unbounded

following

# 包括本行和之後所有的行

rows

between

3preceding

and1

following

# 從前三行到下一行

# 以年為分組,移動的累計求近三個月營業額的情況

select

month

, amount,

sum(amount)

over

(partition

byyear

order

bymonth

rows

between

2preceding

andcurrent

row)

from trade

3、排序視窗函式

3.1 row_number()

select*,

row_number(

)over

(partition

by goods order

by trade_date desc

)as rank

from trade

3.2 rank()
select*,

rank(

)over

(partition

by goods order

by trade_date desc

)as rank

from trade

3.3 dense_rank()
select*,

dense_rank(

)over

(partition

by goods order

by trade_date desc

)as rank

from trade

4、切分視窗函式
# 將支付金額按順序分成5份,即分成5個等級

select*,

ntilt(5)

over

(partition

by goods order

by amount desc)as

level

from trade

5、偏移視窗函式

5.1 lag()

select id,

lag(name,

1, name)

over

(order

by id)

as lag_name

from person

5.2 lead()
select id,

lead(name,

1, name)

over

(order

by id)

as lead_name

from person

6、first_value() , last_value()

6.1 first_value()

select id,

first_value(url)

over

(partition

by cookieid order

by createtime)

as first1

from person

6.2 last_value()
select id,

last_value(url)

over

(partition

by cookieid order

by createtime)

as last1

from person

Hive之視窗函式

對一定視窗期內的資料進行聚合。示例 select sum a.pv over partition by cookieid order by create time rows between 3 preceding and current row as pv1,sum a.pv over partit...

hive sql之 視窗函式。

一 row number 函式 區別於其它排序函式,相當於多了乙個排序的列。資料準備 name money ming 12 yang 23 ming 35 ming 54 yang 43 1 按照其中money 進行排序並增加一行。select name,money,row number over ...

Scala之視窗函式排序

scala視窗函式這排序rank,重複排序和不重複排序 1 引入包 import org.apache.spark.sql.expressions.window import spark.implicits.2.建立測試的df,可以直接貼上測試。3.選擇按name分組,按score排序,且倒序。va...