Answer a question

I have a data model like the following which is simplified to show you only this problem (SQL Fiddle Link at the bottom):

enter image description here

A person is represented in the database as a meta table row with a name and with multiple attributes which are stored in the data table as key-value pair (key and value are in separate columns).

Expected Result

Now I would like to retrieve all users with all their attributes. The attributes should be returned as json object in a separate column. For example:

name, data
Florian, { "age":23, "color":"blue" }
Markus, { "age":24, "color":"green" }

My Approach

Now my problem is, that I couldn't find a way to create a key-value pair in postgres. I tried following:

SELECT
  name,
  array_to_json(array_agg(row(d.key, d.value))) AS data
FROM meta AS m
JOIN (
  SELECT d.fk_id, d.key, d.value AS value FROM data AS d
  ) AS d
ON d.fk_id = m.id
GROUP BY m.name;

But it returns this as data column:

[{"f1":"age","f2":24},{"f1":"color","f2":"blue"}]

Other Solutions

I know there is the function crosstab which enables me to turn the data table into a key as column and value as row table. But this is not dynamic. And I don't know how many attributes a person has in the data table. So this is not an option.

I could also create a json like string with the two row values and aggregate them. But maybe there is a nicer solution.

And no, it is not possible to change the data-model because the real data model is already in use of multiple parties.

SQLFiddle

Check and test out the fiddle i've created for this question: http://sqlfiddle.com/#!15/bd579/14

Answers

Use the aggregate function json_object_agg(key, value):

select 
    name, 
    json_object_agg(key, value) as data
from data
join meta on fk_id = id
group by 1;

Db<>Fiddle.

The function was introduced in Postgres 9.4.

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐