Skip to content
Advertisement

How to deal with JSON column while using GROUP BY

I’m using a query similar to the below one, address is JSON TYPE.

SELECT id, name, MAX(salary), age, adress FROM test group by id, name, age

But getting below error:

SQL Error [42883]: ERROR: could not identify an equality operator for type json
  Position: 152

I’m trying to get the data of a person who has the max salary for his age and I need to include adress filed which should be JSON

So, Is the there any way to achieve this or is this practically possible ?

Note:- postgres db

Advertisement

Answer

I’d go with DISTINCT ON() instead:

SELECT DISTINCT ON (age) id, name, salary, age, adress
FROM test
ORDER BY age, salary desc

The DISTINCT ON (age) will give you one row for each age. The one with the highest salary, as the ORDER BY decides.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement