Tengo un campo de texto llamado json_col en mi tabla de postgres (versión 10). Estoy tratando de expandir las dos matrices MyArray e impressions en varias filas usando SQL
select json_col::json -> 'content'->>'objectID' as objectID ,json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue ,json_array_elements(json_col::json -> 'content'->'impressions')->>'intent' as intent from my_pg_tableData de muestra
{ "content": { "objectID": "ABC", "ObjectType": "MyType", "MyArray": [ "Blue", "Black" ], "impressions": [ { "intent": "Large" }, { "intent": "Small" }, { "intent": "Regular" }, { "intent": "Medium" } ] } }En la salida, obtengo la matriz externa (impresiones) como se esperaba. Además, la primera matriz (MyArray) se expande a varias filas, pero no crea una fila para cada uno de los registros creados por la primera expansión de la matriz.
Estoy obteniendo resultados como este.
objectID intent MyArrayValue ABC Large Blue ABC Small Black ABC Regular [NULL] ABC Medium [NULL]Pero estoy buscando una salida como la siguiente.
objectID intent MyArrayValue ABC Large Blue ABC Large Black ABC Small Blue ABC Small Black ABC Regular Blue ABC Regular Black ABC Medium Blue ABC Medium BlackPor favor, hágamelo saber si tiene alguna entrada.
Puedes probarlo de esta manera:
with cte as ( select json_col::json -> 'content'->>'objectID' as objectID ,json_array_elements(json_col::json -> 'content'->'impressions')->>'intent' as intent from my_pg_table ), cte1 as ( select json_col::json -> 'content'->>'objectID' as objectID ,json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue from my_pg_table ) select t1.objectID,t1.intent,t2.myarrayvalue from cte t1 inner join cte1 t2 on t1.objectID=t2.objectIDUtilice la función en juntas laterales:
select json_col::json -> 'content'->>'objectID' as objectID, impressions->>'intent' as intent, MyArrayValue from my_pg_table cross join json_array_elements(json_col::json -> 'content'->'impressions') as impressions cross join json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue