SQL怎么输出前n个记录? n是中间计算得到的,不支持变量传递

需求:

表 people_crowed_test

       
按view_num排序后,输出该表的记录前30%的aid, buyer_id;

需求场景下的诸多限制: 

1) 不支持变量赋值,也就是无法把中间结果保存到变量了。 自然也无法支持  limit {变量}

2) (select a from ...) 这种数据无法用于where 中的a> ... 比较中

3)不支持 Top N

 

终于捣鼓出了一种死笨死笨的写法,希望以后有改善。

-- 把中间结果 num 保存在表中
-- 并计算其30%后的四舍五入整数
insert overwrite table test_record_count
select
         'old',
     num
from 
         (select round(count(*)*0.3) num from people_crowed_test)a;

-- 对象表排序,然后与num表join,rank 输出
insert overwrite table crowed_old_test
select
         aid,
     buyer_id
from 
(
    select
       'old' group_type,
       aid,
       buyer_id,
           rank() over(partition by rank_id order by view_num desc) as rn
    from
    (
    select 
           'same'   rank_id,   --  为了对所有记录排序,设置的by 键
       aid,
       buyer_id,
       view_num
    from people_crowed_test
    )a1
)a 
join (select  group_type, num from test_record_count where group_type='old')b
on a.group_type=b.group_type   
-- group_type字段 是强制给两个join表添加的join key
where a.rn<b.num;
原文地址:https://www.cnblogs.com/skyEva/p/5439099.html