Oracle row_number分析函數簡化了我們的很多操作

來源:互聯網
上載者:User

//問題:  
CI  MSISDN      CNT  
18802   13009060195 9  
18830   13009060195 1  
18837   13009060195 2  
18829   13009063333 5  
18830   13009063333 7  
18847   13009063333 4  
//結果:  
CI  MSISDN      CNT  
18802   13009060195 9  
18830   13009063333 7  
//此問題是想把MSISDN相同的項的CNT查詢出來  
//碰到此問題,我是這麼思考的:  
//首先,將MSISDN相同的項的CNT查詢出來,構成一個結果集:  
with t as(  
     select '18802' ci,'13009060195' msisdn,9 cnt from dual union all  
     select '18830','13009060195',1 from dual union all  
     select '18837','13009060195',2 from dual union all  
     select '18829','13009063333',5 from dual union all  
     select '18830','13009063333',7 from dual union all  
     select '18847','13009063333',4 from dual)  
select msisdn,max(cnt) cnt  
from t  
group by msisdn  
--  
MSISDN             CNT  
----------- ----------  
13009060195          9  
13009063333          7  
//其次,將原表與此結構集相匹配,如果MSISDN和CNT都相同的就提出來  
select t.*  
from t,(  
     select msisdn,max(cnt) cnt  
     from t  
     group by msisdn  
     ) b  
where t.msisdn=b.msisdn and   
      t.cnt=b.cnt;  
//這樣就能得到我們想要的結果,如下:  
CI    MSISDN             CNT  
----- ----------- ----------  
18802 13009060195          9  
18830 13009063333          7  
//分析:  
//這不是一個很難的問題,  
/*********分組統計******/ 
//可這又是子查詢,又是表串連的,怎麼那麼費事呢?  
//肯定還有更好的解決方案:  
select ci,msisdn,cnt   
from (select ci,  
             msisdn,  
             cnt,  
             row_number()over(partition by msisdn order by cnt desc) rn from t)  
where rn=1; 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.