SELECT key1, key2, JSON_ARRAYAGG(foo) foo, JSON_ARRAYAGG(bar) bar FROM (
select 1 as key1, 2 as key2, '1.0' as foo, 'A' as bar from dual
UNION
select 1, 2, '2.0' , 'A' as bar from dual
UNION
select 3, 4, '2.0' , 'A' as bar from dual
UNION
select 3, 4, '2.0' , 'B' as bar from dual
UNION
select 3, 4, '2.0' , 'B' as bar from dual) z
GROUP BY key1, key2
The query returns following result:
1 2 ["1.0","2.0"] ["A","A"]
3 4 ["2.0","2.0"] ["A","B"]
I was expecting
1 2 ["1.0","2.0"] ["A"]
3 4 ["2.0"] ["A","B"]
I seems that JSON_ARRAYAGG doesn’t support DISTINCT, any suggestions?
2
Answers
Yeah thats not implemented (yet). The workaround is to de-dup the data in advance, eg
In addition to what Connor wrote alternative workarounds could be
aggregate function + row_number for de-duplication (
rn
can be moved intowhere clause
instead ofdecode
depending on circumstances but in such scenariodistinct
is more preferable)nested aggregates in a correlated scalar (keep in mind that each correlated scalar is, in fact, an implicit
join
)