So I have a PostgreSQL (TimescaleDB) table that looks like this:
╔════════════════════════════╦═══════╦═══════╗
║ tags ║ time ║ value ║
╠════════════════════════════╬═══════╬═══════╣
║ {"a": "test", "c": "test"} ║ 10:24 ║ 123 ║
║ {"b": "test", "c": "test"} ║ 10:25 ║ 110 ║
║ {"b": "test"} ║ 10:26 ║ 130 ║
╚════════════════════════════╩═══════╩═══════╝
And I would like to split the JSON(B) column into multiple columns like this:
╔════════╦════════╦════════╦═══════╦═══════╗
║ a ║ b ║ c ║ time ║ value ║
╠════════╬════════╬════════╬═══════╬═══════╣
║ "test" ║ ║ "test" ║ 10:24 ║ 123 ║
║ ║ "test" ║ "test" ║ 10:25 ║ 110 ║
║ ║ "test" ║ ║ 10:26 ║ 130 ║
╚════════╩════════╩════════╩═══════╩═══════╝
I looked into the JSON Processing Functions and it seems that those require finding all the JSON(B) attributes and types. Is there a way to do this automatically?
There is no way to make this dynamic. The number (and types) of all columns of a query must be known to the database when parsing the statement, long before it's actually executed.
If you always have the same structure you can create a type:
create type tag_type as (a text, b text, c text);
and then use jsonb_populate_record()
select (jsonb_populate_record(null::tag_type, tags)).*, time, value
from the_table;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.