Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

count distinct records from jsonb column

I have a column stored as jsonb which is an array of number. Values look like this

enter image description here

I’d like to count the total distinct values from this column. I can get the distinct values like below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT DISTINCT JSONB_ARRAY_ELEMENTS_TEXT(aimjoined) AS aims FROM mytable;

I can’t figure out how to count the total number of occurences for each of the unique values.

>Solution :

First flatten the table using a lateral join and then do a trivial group by.

SELECT aims::numeric, count(*)
FROM mytable, 
lateral jsonb_array_elements(aimjoined) AS aims
group by aims;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading