我不明白为什么在这种情况下列correct
和incorrect
具有不同的值。老实说-这似乎很奇怪,因为它是有效的SQL,因为cross apply
部分不是由于group by
而计算出的聚合函数。
with Foo as (
select 1 as id, 'foo_1' as txt from Dual union all
select 2, 'foo_2' from Dual),
Bar as (
select 1 as id, 'bar_1' as txt, 1 as foo_id from Dual union all
select 2, 'bar_2', 1 from Dual union all
select 3, 'bar_3', 1 from Dual union all
select 4, 'bar_4', 2 from Dual)
select
f.id,
listagg(b.txt, ', ') within group (order by b.id) as correct,
incorrect
from Foo f
join Bar b on f.id = b.foo_id
cross apply (
select
listagg(txt, ', ') within group (order by id) as incorrect
from Bar
where foo_id = f.id)
group by f.id
order by f.id;
结果是:
ID CORRECT INCORRECT
1 bar_1, bar_2, bar_3 bar_4
2 bar_4 bar_4
但是当我确实删除group by
部分并添加distinct
时,如下所示:
with Foo as (
select 1 as id, 'foo_1' as txt from Dual union all
select 2, 'foo_2' from Dual),
Bar as (
select 1 as id, 'bar_1' as txt, 1 as foo_id from Dual union all
select 2, 'bar_2', 1 from Dual union all
select 3, 'bar_3', 1 from Dual union all
select 4, 'bar_4', 2 from Dual)
select distinct
f.id,
incorrect_now_correct
from Foo f
join Bar b on f.id = b.foo_id
cross apply (
select
listagg(txt, ', ') within group (order by id) as incorrect_now_correct
from Bar
where foo_id = f.id)
order by f.id;
我确实得到以下结果:
ID INCORRECT_NOW_CORRECT
1 bar_1, bar_2, bar_3
2 bar_4
这是我在第一个查询的incorrect
列中期望的结果。
使用group by
子句时对group by
子句的处理是否有所不同?直到现在,我还只是认为这更像是与子查询的智能联接。将incorrect
添加到group by
部分使它按应有的方式工作,没有它,其行为类似于第一个查询的结果中所述。它会编译,运行并返回一个有点随机的值。
编辑:数据库版本为 Oracle Database 12c企业版12.1.0.2.0