首页 > 解决方案 > SQL如何从一列的每个间隔中选择n行

问题描述

例如,表格看起来像

一个 b C
1 1 1
2 1 1
3 1 1
4 1 1
5 1 1
6 1 1
7 1 1
8 1 1
9 1 1
10 1 1
11 1 1

我想根据 a 列从每个间隔中随机选择 2 行,其中 a ~ [0, 2], a ~ [4, 6], a ~ [9-20]。

另一种更复杂的情况是根据多列从每个区间中选择 n 行,例如在这种情况下,区间将是 a ~ [0, 2], a ~ [4, 6], b ~ [7, 9], ...

有没有办法只用 SQL 来做到这一点?

标签: sqlsnowflake-cloud-data-platform

解决方案


找出每行属于哪个区间,按区间 id 随机分区排序,获取每个区间的前 n 行:

create transient table mytable as
select seq8() id, random() data
from table(generator(rowcount => 100)) v;

create transient table intervals as
select 0 i_start, 6 i_end, 2 random_rows
union all select 7, 20, 1
union all select 21, 30, 3
union all select 31, 50, 1;

select *
from (
    select *
      , row_number() over(partition by i_start order by random()) rn
    from mytable a
    join intervals b
    on a.id between b.i_start and b.i_end
)
where rn<=random_rows

在此处输入图像描述

编辑:更短更干净。

select a.*
from mytable a
join intervals b
on a.id between b.i_start and b.i_end
qualify row_number() over(partition by i_start order by random()) <= random_rows

推荐阅读