已知原表数据如下:
要求实现如下效果:
--创建表 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;
时间: 2024-11-06 09:52:00