????? row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根據(jù)COL1分組,在分組內部根據(jù) COL2排序,而此函數(shù)計算的值就表示每組內部排序后的順序編號(組內連續(xù)的唯一的).
??????與rownum的區(qū)別在于:使用rownum進行排序的時候是先對結果集加入偽列rownum然后再進行排序,而此函數(shù)在包含排序從句后是先排序再計算行號碼. row_number()和rownum差不多,功能更強一點(可以在各個分組內從1開時排序).
????? rank()是跳躍排序,有兩個第二名時接下來就是第四名(同樣是在各個分組內).
????? dense_rank()l是連續(xù)排序,有兩個第二名時仍然跟著第三名。相比之下row_number是沒有重復值的 .
????? lag(arg1,arg2,arg3): arg1是從其他行返回的表達式 arg2是希望檢索的當前行分區(qū)的偏移量。是一個正的偏移量,時一個往回檢索以前的行的數(shù)目。 arg3是在arg2表示的數(shù)目超出了分組的范圍時返回的值。
create table a ( id number(8) not null, val number(8) ) /
insert into a(id,val) values(1,5);
insert into a(id,val) values(2,8);
insert into a(id,val) values(3,8);
?insert into a(id,val) values(5,8);
?insert into a(id,val) values(9,6);
insert into a(id,val) values(11,6);
insert into a(id,val) values(22,8);
insert into a(id,val) values(40,8);
?insert into a(id,val) values(41,5);
commit;
select * from a order by id;
--[查詢語句]--
select val,count(*) from ( select id,val,row_number() over (order by id) - row_number() over (partition by val order by id) x from a ) group by val,x order by min(id);
--[解析]--
select id,val,row_number() over (order by id) x from a; //按id進行排序
select id,val,row_number() over (partition by val order by id) x from a; //按val分組,分組內按id排序
select id,val,row_number() over (order by id) - row_number() over (partition by val order by id) x from a;//id排序值 減去 val分組內id排序值 = 連續(xù)相同值的排序值
更多文章、技術交流、商務合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
