一个表里的两个字端,一个机型,一个周,要展示成每周的top10 机型,用一个SQL实现
原始数据显示:
jx | 周 | 销量 |
iphone | ww1 | 11 |
iphone | ww1 | 22 |
iphone | ww2 | 34 |
huawei | ww1 | 21 |
huawei | ww1 | 1 |
huawei | ww2 | 33 |
然后我们需要做些处理,展示成如下
select jx,sum(case when week=202136 then cnt else 0 end) as ww1,
sum(case when week=202135 then cnt else 0 end) as ww2
from (
select week,jx,cnt,row_number() over(partition by week order by cnt desc ) as row
from (select week,jx,sum(cnt) as cnt from table_test group by 1,2)
where week = 202136 or week =202135
having row <20
)
group by 1 order by ww1 desc
jx | ww1 | ww2 |
iphone | 23 | 34 |
huawei | 22 | 33 |
so esay