PostgreSql : Json Array to Rows using Lateral Join

前端 未结 4 1006
误落风尘
误落风尘 2020-12-12 06:17

I have two following JSON Array in details field of my table and need to evaluate the query as I use in another relational table.

{
    \"city\": \"London\",         


        
4条回答
  •  再見小時候
    2020-12-12 06:50

    Seems you need WITH ORDINALITY along with LEFT JOIN LATERALs to match the corresponding elements of the arrays due to the order in the arrays, respectively :

    SELECT q.elm AS quantities, p.elm AS prices, 
           AVG(p.elm::float/q.elm::float) AS ratio
      FROM my_table t0
      LEFT JOIN LATERAL jsonb_array_elements(details -> 'quantities') 
        WITH ORDINALITY AS q(elm, i) ON TRUE
      LEFT JOIN LATERAL jsonb_array_elements(details -> 'prices') 
        WITH ORDINALITY AS p(elm, i) ON q.i = p.i
      LEFT JOIN LATERAL jsonb_array_elements(details -> 'dates') 
        WITH ORDINALITY AS d(elm, i) ON d.i = q.i
     WHERE t0.details ->> 'city' = 'London'   
     GROUP BY q.elm, p.elm;
    

    Demo

提交回复
热议问题