0

I have JSONB casted column in table that I'd like to represent as a comma separated list in a single column. I've tried a million different approaches and am coming up short. I can't find anything in the Postgres docs that addresses this particular situation, so hoping for some help!

The table in question looks a little like this:

date       | order_id | sales_reps
2019-12-01 | 1234     | [{"id": 100, "user": "Jane Doe"}, {"id": 101, "user": "John Doe"}]

I'd like to render it as:

date       | order_id | sales_reps
2019-12-01 | 1234     | Jane Doe, John Doe

I'm able to get relatively close with:

select
    date,
    order_id, 
    (select jsonb_agg(t -> 'user') from jsonb_array_elements(sales_reps::jsonb) as x(t)) as sales_reps
from table
date       | order_id | sales_reps
2019-12-01 | 1234     | ["Jane Doe", "John Doe"]

But for the life of me I can't seem to get the output I want - have tried a ton of aggregators and jsonb functions to no avail.

1 Answer 1

3

Use the ->> operator to get json values as text and the string_agg() aggregate:

select
    date,
    order_id,
    (
        select string_agg(t->>'user', ',') 
        from jsonb_array_elements(sales_reps::jsonb) as x(t)
    ) as sales_reps
from my_table

Db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.