0

How to count the unique nested key/values in a json in postgres?

Each user record has a json column called hobby_years which is structured like below but differs from user to user.

Example hobby_years value for a user:

{
    "soccer": {
        "2006": 1,
        "2007": 1
    },
    "skiing": {},
    "basketball": {
        "2006": 1,
        "2016": 1,
        "2017": 1,
        "2018": 1
    },
    "painting": {
        "2008": 1,
        "2009": 1,
        "2014": 1,
        "2015": 1,
        "2016": 1
    }
}

I'd like to know how many unique years exist across one or more specific hobbies. Ie: soccer and basketball - which should return 5.

Alternatively, I have the option to structure data as below if it would make this activity easier

{
    "soccer": [2006, 2007],
    "skiing": [],
    "basketball": [2006, 2016, 2017, 2018],
    "painting": [2008, 2009, 2014, 2015, 2016]
}

Is this possible?

1 Answer 1

1

Something like this?

SELECT
        name, -- or whatever field you want to use to identify the user
        (SELECT COUNT(year)
        FROM (
                SELECT DISTINCT JSON_ARRAY_ELEMENTS(value)::TEXT AS year
                FROM JSON_EACH(hobby_years)
                WHERE key IN ('soccer', 'basketball')) years
        ) AS count
FROM users
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.