0

This is jsonb field data:

[
   {'name': 'pratha', 'email': '[email protected]', 'sub': { 'id': 1 } },
   {'name': 'pratha', 'email': '[email protected]', 'sub': { 'id': 2 } }
]

When I want to get name and email fields, I get duplicate fields.

This is query:

SELECT jae.e->>'name', jae.e->>'email'
       FROM survey_results sr
            CROSS JOIN LATERAL jsonb_array_elements(sr.data_field) jae (e)
            GROUP BY jae.e->>'name', jae.e->>'email'

In this data, both objects' name is pratha but email is different. What I want to is grab one pratha and latest email in array.

Is it possible?

Actual Result:

pratha    [email protected]
pratha    [email protected]

Expected Result:

pratha    [email protected]

I only need name and email fields therefore, I want to group them by name.

See here: http://sqlfiddle.com/#!17/9b55f/2

1 Answer 1

1

You've not explained what "latest email" means, but I presume you want the record with the highest sub->id

You may use DISTINCT ON to get a highest in a group.

SELECT DISTINCT ON (jae.e->>'name') --for every name
    jae.e->>'name'  as name, 
    jae.e->>'email' as email
       FROM survey_results sr
         CROSS JOIN LATERAL jsonb_array_elements(sr.data_field)  jae (e)
       ORDER BY jae.e->>'name', jae.e->'sub'->>'id' desc 
                                         --^ return only the row with the highest id

DEMO

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.