1.窗口函數(shù)的基本用法如下:
window_name() over ([partition_defintion]|[order_definition]|[frame_definition])
其中寂纪,over是關(guān)鍵字烛卧,用來指定函數(shù)執(zhí)行的窗口范圍虎谢,如果后面括號中什么都不寫,則意味著窗口包含滿足where條件的所有行膘盖,窗口函數(shù)基于所有行進(jìn)行計(jì)算;如果不為空妇斤,則支持以下四種語法來設(shè)置窗口:
(1)window_function_name:給窗口指定一個別名茎截,如果SQL中涉及的窗口較多,采用別名可以看起來更清晰易讀油狂。
(2)partition子句:窗口按照那些字段進(jìn)行分組历恐,窗口函數(shù)在不同的分組上分別執(zhí)行。上面的例子就按照用戶id進(jìn)行了分組专筷。在每個用戶id上弱贼,按照order by的順序分別生成從1開始的順序編號。
(3)order by子句:按照哪些字段進(jìn)行排序磷蛹,窗口函數(shù)將按照排序后的記錄順序進(jìn)行編號吮旅。可以和partition子句配合使用味咳,也可以單獨(dú)使用庇勃。上例中二者同時使用,如果沒有partition子句槽驶,則會按照所有用戶的訂單金額排序來生成序號匪凉。
(4)frame子句:frame是當(dāng)前分區(qū)的一個子集,子句用來定義子集的規(guī)則捺檬,通常用來作為滑動窗口使用再层。比如要根據(jù)每個訂單動態(tài)計(jì)算包括本訂單和按時間順序前后兩個訂單的平均訂單金額,則可以設(shè)置如下frame子句來創(chuàng)建滑動窗口
摘自http://blog.sina.com.cn/s/blog_141b32d280102ym7h.html
2.窗口函數(shù)可以和聚類函數(shù)一起使用
可以解決許多分組求和的問題堡纬,并且可以帶出來一些其他字段聂受。
mysql> SELECT
year, country, product, profit,
SUM(profit) OVER() AS total_profit,
SUM(profit) OVER(PARTITION BY country) AS country_profit
FROM sales
ORDER BY country, year, product, profit;
year | country | product | profit | total_profit | country_profit |
---|---|---|---|---|---|
2000 | Finland | Computer | 1500 | 7535 | 1610 |
2000 | Finland | Phone | 100 | 7535 | 1610 |
2001 | Finland | Phone | 10 | 7535 | 1610 |
2000 | India | Calculator | 75 | 7535 | 1350 |
2000 | India | Calculator | 75 | 7535 | 1350 |
2000 | India | Computer | 1200 | 7535 | 1350 |
2000 | USA | Calculator | 75 | 7535 | 4575 |
2000 | USA | Computer | 1500 | 7535 | 4575 |
2001 | USA | Calculator | 50 | 7535 | 4575 |
2001 | USA | Computer | 1200 | 7535 | 4575 |
2001 | USA | Computer | 1500 | 7535 | 4575 |
2001 | USA | TV | 100 | 7535 | 4575 |
2001 | USA | TV | 150 | 7535 | 4575 |
3.mysql專門提供了窗口函數(shù)
CUME_DIST()
DENSE_RANK()
FIRST_VALUE()
LAG()
LAST_VALUE()
LEAD()
NTH_VALUE()
NTILE()
PERCENT_RANK()
RANK()
ROW_NUMBER()
mysql> SELECT
year, country, product, profit,
ROW_NUMBER() OVER(PARTITION BY country) AS row_num1,
ROW_NUMBER() OVER(PARTITION BY country ORDER BY year, product) AS row_num2
FROM sales;
year | country | product | profit | row_num1 | row_num2 |
---|---|---|---|---|---|
2000 | Finland | Computer | 1500 | 2 | 1 |
2000 | Finland | Phone | 100 | 1 | 2 |
2001 | Finland | Phone | 10 | 3 | 3 |
2000 | India | Calculator | 75 | 2 | 1 |
2000 | India | Calculator | 75 | 3 | 2 |
2000 | India | Computer | 1200 | 1 | 3 |
2000 | USA | Calculator | 75 | 5 | 1 |
2000 | USA | Computer | 1500 | 4 | 2 |
2001 | USA | Calculator | 50 | 2 | 3 |
2001 | USA | Computer | 1500 | 3 | 4 |
2001 | USA | Computer | 1200 | 7 | 5 |
2001 | USA | TV | 150 | 1 | 6 |
2001 | USA | TV | 100 | 6 | 7 |