【发布时间】:2019-01-11 06:28:45
【问题描述】:
假设以下简化架构:
create table main_table
(
a number,
b number,
c number
);
create table other_table
(
c number,
d number
)
现在,我想要实现的目标: 我有一个关于 main_table 的查询,按 a、b 分组。 我需要在 select 子句中的子查询中使用“c 的所有值”来从其他表中获取一些数据。 很遗憾,我无法加入另一张桌子。
伪代码是:
select mt.a,
mt.b,
(select /* some aggregated value */
from other_table ot
where ot.c in (all_values_of_c_within_group)
)
from main table mt
group by mt.a, mt.b
我知道有两种方法可以解决这个问题:
- 在 other_table 上使用连接,然后从那里聚合值 - 不幸的是,我不能这样做,因为真正的查询是如何构造的(3 个嵌套视图、800 个 sloc、30 个分组值 - 长篇大论)
- 使用 listagg,然后将其与 'instr' 一起'delistagg'。伪代码:
/*(...)*/
(select /* some_aggregated_value */
from other_table ot
where instr(',' || listagg(
to_char(mt.c), ',') within group (order by 1),
',' || ot.c) > 0
)
/*(...)*/
但这只是糟糕的代码,它会自动阻止在 other_table.c 上使用任何可能存在的索引。
是否有正确获取“组内列的所有值”的语法?
【问题讨论】:
-
一些示例数据和预期结果会很有用。