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\",
Basically, what Abelisto said. Just a couple of improvements and some explanation:
SELECT to_date(d, 'DD.MM.YYYY') AS date -- ①
, quantity, price
, round(price / quantity, 4) AS ratio -- ③, ④
FROM my_table
CROSS JOIN LATERAL ( -- ②
SELECT json_array_elements_text(details->'dates' ) AS d -- ①
, json_array_elements_text(details->'quantities')::int AS quantity -- ③
, json_array_elements_text(details->'prices' )::numeric AS price -- ③
) AS data
WHERE details->>'city' = 'London';
db<>fiddle here
① Date strings are interpreted depending on locale settings and session variables by default. Do it the clean way with to_date().
② Multiple set-returning functions in the SELECT list behave in surprising ways up until Postgres 10 if the number of resulting rows is not exactly the same for all. (Consider upgrading. In any case.) See:
③ In your original query AVG(quantities/prices::float) makes no sense in combination with group by quantities, prices. Neither does quantities/prices on its own. I fixed as I saw fit, and threw in round() to format output.
④ If quantity can be 0 defend against division by 0 with NULLIF:
, round(price / NULLIF(quantity, 0), 4) AS ratio