简体   繁体   中英

Pivoting AWS Redshift SUPER data

I have a following table structure:

server_id server_databases
1 [{"name": "mssql", "count": 12},{"name": "postgresql", "count": 1}]
2 []
3 null

What I want to receive as a result(I want to keep servers 2 and 3 if it would be null or empty object doesn't matter):

server_id databases
1 {"mssql": 12, "postgresql": 1}
2 null
3 null

I've tried to build json myself

SELECT server_id,
       (
           select '{' || listagg('"' || x.name || '":' || x.count, ',') || '}' as clientdatabases
           from (
                    select cb."name"::varchar as name, sum(cb."count")::int as count from e.server_databases as cb group by name
                ) x
       )
FROM my_table e

But it fails with interestiong error

[XX000] ERROR: Query unsupported due to an internal error. Detail: Unsupported witness case Where: nested_decorrelate_calc_witness_unsupported|calc_witness

It looks like PartiQL supports such cases , but I have no idea how to implement it. I will use UDF for now. But, if you can help me with a "native" solution, it would be amazing.

Use ISNULL in count:

SELECT server_id,
       (
           select '{' || listagg('"' || x.name || '":' || x.count, ',') || '}' as clientdatabases
           from (
                    select cb."name"::varchar as name, ISNULL(sum(cb."count")::int,0) as count from e.server_databases as cb group by name
                ) x
       )
FROM my_table e

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM