sql - 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 来做到这一点?
解决方案
找出每行属于哪个区间,按区间 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
推荐阅读
- python-3.x - 如何将 coc-pyright 设置为不对方法中未使用的 self 参数发出警告?
- format - 数据洞察自定义数字格式
- html - 网站抓取:网站搜索框没有价值
- ilnumerics - 在 Visual Studio 输出中禁用 ILNumerics 缓冲区消息
- powershell - PowerShell:IF 语句中的多个条件
- excel - VBA:从工作表中删除信息
- docker - Docker pull 找不到“最新”标签
- python - ROS Noetic 没有名为 'rqt_py_common' 的模块
- javascript - 如何使用表格方法分页实现卡片分页
- mysql - SQLalchemy Json-configured varchar:如何过滤