I have to get some columns as is and some columns from a query as JSON document. The as is column names are known to me but rest are dynamic columns so there are not known beforehand.
Below is the query like
select col1,col2,col3,
sum(col4) as col4,
sum(col5) as col5
from my_table
group by col1,col2,col3;
here col4,col5 names are unknown to me as they are been fetched dynamically.
Suppost my_table data looks like
The expected result is like below
I tried
select JSON_OBJECT(*) from
(
select col1,col2,col3,
sum(col4) as col4,
sum(col5) as col5
from my_table
group by col1,col2,col3
);
But obviously it does not yield expected output.
I’m on 19c DB version 19.17
Any help or suggestion would be great help!
2
Answers
It’s kinda hacky, but you could:
json_object(*)
to convert the whole row tojson
json_transform
*, which you can use to remove unwanted attributesSo you could do something like:
json_transform
is a 21c feature that’s been backported to 19c in 19.10.You may achieve this by using Polymorphic Table Function available since 18c.
Define the function that will project only specific columns and serialize others into JSON. An implementation is below.
fiddle