CUME_DIST() 是累計分布函數中的一種,另外還有NTH_VALUE()與 NTILE()
★1.CUME_DIST()是一個計算公式的結果值,
公式:當升序排列,計算小於等於當前值的行數/總行數(number of rows ≤ current row)/(total number of rows)。
當降序排列,計算大於等於當前值的行數/總行數。
拿個具體的例子來說:
某表的結構與表數據如上圖
求: 按部門統計小於等於當前工資的人數占部門總人數的比例
select name,dept,salary,cume_dist() over (partition by product_type order by sale_price desc) as result from salary;
select name,dept,salary,cume_dist() over (partition by product_type order by sale_price asc) as result from salary;
★2.NTH_VALUE() :取指定排名行的數據
語法:NTH_VALUE (measure_expr, n)
[ FROM { FIRST | LAST } ][ { RESPECT | IGNORE } NULLS ] OVER (analytic_clause)
以前版本的分析函數,提供了FIRST_VALUE和LAST_VALUE的功能,而11gr2中,Oracle增加了一個NTH_VALUE的功能,這個功能包含了FIRST_VALUE和LAST_VALUE的功能,同時還可以取任意的正數或倒數的記錄 。
select ID, NAME ,DEPT, nth_value(NAME,3) over (order by ID) as A nth_value(NAME ,4) over (order by ID) as B nth_value(NAME ,1) from first over (order by ID) as C nth_value(NAME ,2) from first over (partition by DEPT order by ID) as D, nth_value(NAME ,2) FROM FIRST over (order by ID) as E, nth_value(NAME ,4) FROM LAST over (order by ID) as F from salary
結果是:
1.從上面的查詢結果我們可以看出nth_value(product_name,3)是根據后面的分組的原則(分組或者不分組)找到已product_name排序的第三個值作為該列的值,如果沒取到該值為空
tips:在剛接觸窗口函數的時候,曾寫過下面的SQL,目的是查詢根據id排序第三名的數據
SELECT * FROM salary WHERE row_number() over (order by id)=3
但是上面的函數報錯提示:ORA-30483:window函數在此禁用
現在來看,上面的nth_value(NAME,3) over (order by ID) 就正好解決了這個問題
2.nth_value(NAME ,1) from first over (order by ID) 是根據查詢出的排序結果取第一行數據的值作為該列的值,如果沒取到該值為空
3.nth_value(NAME ,4) FROM LAST over (order by ID) 這個的用法是從排序的是4名開始往后取依次錯開作為該行的值
疑問:FROM LAST 與FROM FIRST在作用上沒對應?
★3.NTILE() 根據設定的組數對記錄進行平均分組並編號,不能完全分組的繼續從1開始往下編
select ID, NAME ,DEPT, ntile(NAME,1) over (order by ID) as A, ntile(NAME,2) over (order by ID) as B, ntile(NAME,3) over (order by ID) as C, ntile(NAME,4) over (order by ID) as D, ntile(NAME,5) over (order by ID) as E, ntile(NAME ,3) over (partition by DEPT order by ID) as AA from salary
結果值: