認識窗口函數
在說窗口函數之前我們先來看一個問題:
假設我們有這樣一張products表:
Snip20171230_1.png
我們想要同時取出產品的名稱、售價,同時列出這件產品對應的商品類型的平均價格?
按照以前我們的子查詢知識我們可以這樣:
select name,
price,
(select avg(price) from products where type = p.type) as type_avg_price
from products p;
Snip20171230_2.png
很好!能夠正確執(zhí)行,但窗口函數有更好的辦法(可以先分類再算平均價格)
select name,
price,
avg(price) over (partition by type) as type_avg_price
from products;
# partition by是按照什么分類的意思
Snip20171230_3.png
這也能很好的執(zhí)行。
下面讓我們把問題難度加大,我們需要同時取出商品名稱、價格、然后按照商品的價格在自己的品類中去排序。
如果用普通的方法比較不好做了,但窗口函數有辦法
select name,
price,
row_number() over (partition by type order by price) as postition
from products;
# row_number是postgresql中的排序函數
# 這里先分類,再排序
Snip20171230_4.png
窗口函數的語法
函數 OVER (<PARTITION BY column_name> <ORDER BY column_name>)
# 函數主要有兩種:(sum avg min max)聚合函數、(rank、dense_rank、row_number)專用窗口函數
# partition by 和 order by 都是可以省略的
小結
- 窗口函數的關鍵點在于,它可以先分類再做函數操作;
- 對比于聚合函數,窗口函數具有聚合的同時保留其它列展示的功能,故稱窗口。