NTILE(n)
- 用於將分組數據按照順序切分成n片,返回當前記錄所在的切片值
NTILE不支持ROWS BETWEEN,比如 NTILE(2) OVER(PARTITION BY cookieid ORDER BY createtime ROWS BETWEEN 3 PRECEDING AND CURRENT ROW)
- 如果切片不均勻,默認增加第一個切片的分布
- 經常用來取前30% 帶有百分之多少比例的記錄什么的
例子:
有下圖的1000家店鋪的價格數據。我們想知道,價格排名前30%的店鋪的平均價格,和后70%的。
思路:
把店鋪均勻的按價格遞減順序分成10片。然后取切片數=1,2,3的即為前30%。
sql:
-- 1 把記錄按價格順序拆分成10片 drop table if exists test_dp_price_rk; create table test_dp_price_rk as select id, price, NTILE(10) OVER (order by price desc) as rn from test_dp_price; -- 2 按片取30%和70%,分別計算平均值 select new_rn, max(case when new_rn=1 then 'avg_price_first_30%' when new_rn=2 then 'avg_price_last_70%' end) as avg_price_name, avg(price) avg_price from ( select id, price, rn, case when rn in (1,2,3) then 1 else 2 end as new_rn from test_dp_price_rk )a group by new_rn;
結果展示: