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) desclast
  
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(5over(order by sum(customer_sales) desc) til
  
4    from user_order
  
5   group by region_id, customer_id;

 

 

 



你可能感兴趣的:(Oracle分析函数详述)