0

In PostgreSQL, I have a table that looks like,

| id | json                            |
| -- | ------------------------------- |
| 1  | {"id":1,"customer":"BANK"}      |
| 1  | {"id":1,"customer":"BANK"}      |
| 2  | {"id":2,"customer":"GOVT"}      |
| 3  | {"id":3,"customer":"BANK"}      |
| 4  | {"id":4,"customer":"ASSET MGR"} |
| 4  | {"id":4,"customer":"ASSET MGR"} |

I need the output of counting the occurrences of customers with unique ids, such as

| customer    | count |
| ----------- | ----- |
| "BANK"      | 2     |
| "GOVT"      | 1     |
| "ASSET MGR" | 1     |

Is there a good way to achieve using PostgreSQL & json? I currently am able to extract the customer and IDs, but am having difficulty counting the unique json objects.

1 Answer 1

2
select count(distinct id), jsondata ->> 'customer' customer 
from data
group by customer
count | customer 
----: | :--------
    1 | ASSET MGR
    2 | BANK     
    1 | GOVT     

db<>fiddle here

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.