SQL 查询每组的topN

首先使用窗口函数在分组并在组内排序

select origin_data_type ,valid_count,
dense_rank() over (partition by origin_data_type order by valid_count ) as ranks 
from base_etl_record ber

SQL 查询每组的topN_第1张图片

然后对排序结果ranks进行筛选

select * from (
select origin_data_type ,valid_count,
dense_rank() over (partition by origin_data_type order by valid_count ) as ranks 
from base_etl_record ber where valid_count !=0 ) as t where t.ranks<=2;

SQL 查询每组的topN_第2张图片

 

你可能感兴趣的:(SQL,学习笔记,sql)