1. 程式人生 > >多層分組排序問題

多層分組排序問題

寫法 分組排序 sm3 src art 創建 div 分享 技術

已知原表數據如下:

技術分享

要求實現如下效果:

技術分享

--創建表
create table tmp as
select 火腿腸 c1, 銷售一部 c2,老王   c3, 1.5 c4 from dual union all
select 玉米   c1, 銷售五部 c2,B老劉  c3, 1   c4 from dual union all
select 筆記本 c1, 銷售一部 c2,老王   c3, 3   c4 from dual union all
select 筆記本 c1, 銷售七部 c2,老張   c3, 3   c4 from dual union
all select 桌子 c1, 銷售九部 c2,老孫 c3, 4 c4 from dual union all select 火腿腸 c1, 銷售五部 c2,老劉 c3, 1.5 c4 from dual union all select 火腿腸 c1, 銷售四部 c2,老趙 c3, 1.5 c4 from dual union all select 玉米 c1, 銷售四部 c2,老李 c3, 1 c4 from dual union all select 筆記本 c1, 銷售七部 c2,老張 c3, 3
c4 from dual union all select 玉米 c1, 銷售五部 c2,A老譚 c3, 1 c4 from dual union all select 玉米 c1, 銷售一部 c2,老柳 c3, 1 c4 from dual union all select 玉米 c1, 銷售一部 c2,老柳 c3, 1 c4 from dual union all select 玉米 c1, 銷售一部 c2,老王 c3, 1 c4 from dual; --寫法1: select rn,c1,rn2,c2,rn3,c3
from(select c1,c2,c3, dense_rank()over(order by sm desc) rn, dense_rank()over(partition by c1 order by sm2 desc) rn2, row_number()over(partition by c1,c2 order by sm3 desc) rn3 from(select distinct t1.c1,t1.c2,t1.c3, sum(t1.c4)over(partition by t1.c1) sm, sum(t1.c4)over(partition by t1.c1,t1.c2) sm2, sum(t1.c4)over(partition by t1.c1,t1.c2,t1.c3) sm3 from tmp t1 ) ) where rn <= 3 and rn2 <= 3 and rn3 = 1 order by rn,rn2,rn3; --寫法2 select rn,c1,rn2,c2,rn3,c3 from(select c1,c2,c3, dense_rank()over(order by sm desc) rn, dense_rank()over(partition by c1 order by sm2 desc) rn2, dense_rank()over(partition by c1,c2 order by sm3 desc) rn3 from(select distinct t1.c1,t1.c2,t1.c3, sum(t1.c4)over(partition by t1.c1) sm, sum(t1.c4)over(partition by t1.c1,t1.c2) sm2, sum(t1.c4)over(partition by t1.c1,t1.c2,t1.c3) sm3 from tmp t1 ) ) where rn <= 3 and rn2 <= 3 and rn3 = 1 order by rn,rn2,rn3;

多層分組排序問題