Oracle分析函数详述
http://www.91linux.com/html/article/database/oracle/20081216/14775.html
?
非常詳細的講述了分析函數的應用.
?
部分例子代碼:
?
1.統計分析數據.
?
select * from (
?select o.cust_nbr customer,
???????? o.region_id region,
???????? sum(o.tot_sales) cust_sales,
???????? sum(sum(o.tot_sales)) over(partition by o.region_id) region_sales
??? from orders_tmp o
?? where o.year = 2001
?? group by o.region_id, o.cust_nbr
?? 
?? ) where cust_sales/region_sales>0.2
?? order by region_sales desc
?
2.排序. Rank,Dense_rank,Row_number
?
select region_id, customer_id, sum(customer_sales) total,
????? rank() over(order by sum(customer_sales) desc) rank,
????? dense_rank() over(order by sum(customer_sales) desc) dense_rank,
?????? row_number() over(order by sum(customer_sales) desc) row_number
???? from user_order
?? group by region_id, customer_id;
?
3.top/bottom n、first/last、ntile
?
1.帶空值的排列
?
?select region_id, customer_id,
?????????? sum(customer_sales) cust_total,
?????????? sum(sum(customer_sales)) over(partition by region_id) reg_total,
?????????? rank() over(partition by region_id 
?????????????????????? order by sum(customer_sales) desc NULLS LAST) rank
????????? from user_order
???????? group by region_id, customer_id;
?
綠色高亮處,NULLS LAST/FIRST告訴Oracle讓空值排名最后后第一。
注意是NULLS,不是NULL。
(經測試,在一般的排序語句中,也可以使用 NULLS LAST/FIRST 指定NULL值的排序位置.)
2.Top/Bottom N查詢
?
【1】找出所有訂單總額排名前3的大客戶:
 SQL>?select?*
SQL>???from?(select?region_id,
SQL>????????????????customer_id,
SQL>????????????????sum(customer_sales)?cust_total,
SQL>????????????????rank()?over(order?by?sum(customer_sales)?desc?NULLS?LAST)?rank
SQL>???????????from?user_order
SQL>??????????group?by?region_id,?customer_id)
SQL>??where?rank?<=?3;
?
3.First/Last排名查詢
?
SQL>?select?min(customer_id)
??2?????????keep?(dense_rank?first?order?by?sum(customer_sales)?desc)?first,
??3?????????min(customer_id)
??4?????????keep?(dense_rank?last?order?by?sum(customer_sales)?desc)?last
??5????from?user_order
??6???group?by?customer_id;
?
?
?
4.按層次查詢
現在我們已經見識了如何通過Oracle的分析函數來獲取Top/Bottom N,第一個,最后一個記錄。有時我們會收到類似下面這樣的需求:找出訂單總額排名前1/5的客戶。
?
SQL>?select?region_id,
??2?????????customer_id,
??3?????????ntile(5)?over(order?by?sum(customer_sales)?desc)?til
??4????from?user_order
??5???group?by?region_id,?customer_id;
?
?
?
總結
以上是生活随笔為你收集整理的Oracle分析函数详述的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: OLTP 数据库特点
 - 下一篇: Linux操作系统下Oracle主要监控