本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
NTILE 範圍函數將分割區中排序的列劃分為指定數量的排名群組,且大小儘可能相等,然後傳回給定列所屬的群組。
語法
NTILE (expr) OVER ( [ PARTITION BY expression_list ] [ ORDER BY order_list ] )
引數
- expr
-
每一個分割區的排名群組數,且結果必須為整數值 (大於 0)。expr 引數必須不可為 Null。
- OVER
-
用於指定視窗分割和排序的子句。OVER 子句不能包含視窗框規格。
- PARTITION BY window_partition
-
選用。OVER 子句中每一個群組的記錄範圍。
- ORDER BY window_ordering
-
選用。此表達式排序每一個分割區內的列。如果省略 ORDER BY 子句,則排名行為相同。
如果 ORDER BY 未產生唯一排序,則列的順序不確定。如需詳細資訊,請參閱範圍函數的資料唯一排序。
傳回類型
BIGINT
範例
下列範例將 2008 年 8 月 26 日 Hamlet 門票的支付價格分成四個排名群組。結果集有 17 列,幾乎平均分散於排名 1 到 4:
select eventname, caldate, pricepaid, ntile(4)
over(order by pricepaid desc) from sales, event, date
where sales.eventid=event.eventid and event.dateid=date.dateid and eventname='Hamlet'
and caldate='2008-08-26'
order by 4;
eventname | caldate | pricepaid | ntile
-----------+------------+-----------+-------
Hamlet | 2008-08-26 | 1883.00 | 1
Hamlet | 2008-08-26 | 1065.00 | 1
Hamlet | 2008-08-26 | 589.00 | 1
Hamlet | 2008-08-26 | 530.00 | 1
Hamlet | 2008-08-26 | 472.00 | 1
Hamlet | 2008-08-26 | 460.00 | 2
Hamlet | 2008-08-26 | 355.00 | 2
Hamlet | 2008-08-26 | 334.00 | 2
Hamlet | 2008-08-26 | 296.00 | 2
Hamlet | 2008-08-26 | 230.00 | 3
Hamlet | 2008-08-26 | 216.00 | 3
Hamlet | 2008-08-26 | 212.00 | 3
Hamlet | 2008-08-26 | 106.00 | 3
Hamlet | 2008-08-26 | 100.00 | 4
Hamlet | 2008-08-26 | 94.00 | 4
Hamlet | 2008-08-26 | 53.00 | 4
Hamlet | 2008-08-26 | 25.00 | 4
(17 rows)