Greenplum 6中按表A限制抽取表B数据填充新表的方法
问题:基于Greenplum按指定数量随机抽取关联IP数据
环境与表结构
我正在使用基于PostgreSQL 9.4的Greenplum 6,现有两张示例表:
表SAMPLE_A
| uniqueId | SampleSz |
|---|---|
| 1 | 25 |
| 2 | 50450 |
| 3 | 9 |
表SAMPLE_B
| IP | uniqueId |
|---|---|
| 1.4.4.5 | (1,2,3) |
| 2.5.6.7 | (2) |
| 3.4.7.8 | (1,3) |
需求描述
需要创建新表,核心逻辑如下:
- 遍历
SAMPLE_A的每个uniqueId,从SAMPLE_B中随机抽取对应SampleSz数量的IP - 抽取条件:目标IP对应的
SAMPLE_B.uniqueId数组中包含当前处理的SAMPLE_A.uniqueId - 按
SAMPLE_A的uniqueId依次处理,最终汇总所有抽取结果
尝试的SQL及问题
我先针对单条记录的逻辑编写了如下SQL,但执行失败:
select i.ip, s.uniqueId from SAMPLE_A s join lateral ( select distinct ip from SAMPLE_B i where s.uniqueId = any(i.uniqueId) -- ORDER BY random() LIMIT s.SampleSz ) i on true
执行时抛出解组错误,且即使能运行,也无法覆盖完整需求场景,这只是我尝试的第一步。
更新:期望结果集
原示例表的数据量太小,结果不具参考性,因此假设SAMPLE_B包含3.4.7.0至3.4.7.255的所有IP,每个IP对应的uniqueId数组都包含1、2、3三个值。此时期望结果规则为:
uniqueId=2:因样本量50450大于IP总数256,返回全部256条IPuniqueId=1:随机返回25条IPuniqueId=3:随机返回9条IP
示例结果片段:
| IP | uniqueId |
|---|---|
| 3.4.7.25 | 3 |
| 3.4.7.5 | 3 |
| 3.4.7.7 | 3 |
| 3.4.7.8 | 3 |
| 3.4.7.84 | 3 |
| 3.4.7.61 | 3 |
| 3.4.7.112 | 3 |
| 3.4.7.125 | 3 |
| 3.4.7.194 | 3 |
| 3.4.7.8 | 1 |
| 3.4.7.1 | 1 |
内容的提问来源于stack exchange,提问作者S Ayo
相关产品推荐
相关产品推荐

