I have a table like below:
object_key | created_by | updated_on | updated_by | attr_type | value_name | value_num |
---|---|---|---|---|---|---|
1 | user1 | 3/21/2021 | user1 | name | John | |
1 | user4 | 4/15/2021 | user3 | mobile_number | 4567865 | |
1 | user3 | 4/21/2021 | user2 | office_number | 2378783 |
I'm trying to pivot using the query:
SELECT object_key,
max(created_on) AS created_on,
max(updated_on) AS updated_on,
max(updated_by) FILTER (WHERE updated_on = max(updated_on)) AS updated_by,
max(array_to_string(value_name, '||'::text)) FILTER (WHERE attr_type = 'name' )as name,
max(array_to_string(value_num, '||'::text)) FILTER (WHERE attr_type = 'mobile_number') AS mobile_number,
max(array_to_string(value_num, '||'::text)) FILTER (WHERE attr_type = 'office_number') AS office_number
FROM object_attributes
GROUP BY object_key;
Pivoted table must be like:
object_key | created_by | updated_on | updated_by | name | mobile_number | office_number |
---|---|---|---|---|---|---|
1 | user1 | 4/21/2021 | user2 | John | 4567865 | 2378783 |
updated_by
should come from a row having highest updated_on
date for each object_key
.
But FILTER (WHERE updated_on = max(updated_on))
is not working in the query.
Is there a way to select updated_by
using the updated_on
in the pivot?