oracle分析函数系列之Top/Bottom N、min() keep First/Last、NTile:排名空处理,查询第一名,最后一名

目录
===============================================

1.带空值的排列
2.Top/Bottom N查询
3.First/Last排名查询
4.按层次查询

一、带空值的排列:

在前面《Oracle开发专题之:分析函数2(Rank、Dense_rank、row_number)》一文中,我们已经知道了如何为一批记录进行全排列、分组排列。假如被排列的数据中含有空值呢?

SQL> select region_id, customer_id,
  
2         sum(customer_sales) cust_sales,
  
3         sum(sum(customer_sales)) over(partition by region_id) ran_total,
  
4         rank() over(partition by region_id
  
5                  order by sum(customer_sales) desc) rank
  
6    from user_order
  
7   group by region_id, customer_id;

 REGION_ID CUSTOMER_ID CUST_SALES  RAN_TOTAL       RANK
---------- ----------- ---------- ---------- ---------- 
        10          31                   6238901          1
        
10          26    1808949    6238901          2
        
10          27    1322747    6238901          3
        
10          30    1216858    6238901          4
        
10          28     986964    6238901          5
        
10          29     903383    6238901          6

我们看到这里有一条记录的CUST_TOTAL字段值为NULL,但居然排在第一名了!显然这不符合情理。所以我们重新调整完善一下我们的排名策略,看看下面的语句:

SQL> select region_id, customer_id,
  
2         sum(customer_sales) cust_total,
  
3         sum(sum(customer_sales)) over(partition by region_id) reg_total,
  
4         rank() over(partition by region_id 
                        
order by sum(customer_sales) desc NULLS LAST) rank
  
5        from user_order
  
6       group by region_id, customer_id;

 REGION_ID CUSTOMER_ID CUST_TOTAL  REG_TOTAL       RANK
---------- ----------- ---------- ---------- ----------

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值