Question

I have a JSON column, named info, with these values:

    {"width":"800, "height":"480"}
    {"width":"800, "height":"480"}
    {"width":"768, "height":"480"}

I need a SQL query to have the output in this format:

    Label   |Count
    ==============
    800x480, 2
    768x480, 1

Where the second value represents the count.

What I managed to do is to extract first value and the count:

    select info->>'width' as label, count(info->>'width') from table_name  GROUP BY 1 ORDER BY 2 DESC LIMIT 5

Which outputs:

    Label   |Count
    ==============
    800, 2
    768, 1
Was it helpful?

Solution

Regular string concatenation should do it. For some reasons, the query fails if you omit the () from the query.

SELECT (info->>'width') || 'x' || (info->>'width') AS label,
    COUNT(info->>'width')
FROM table_name
GROUP BY 1
ORDER BY 2 DESC
LIMIT 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top