Skip to content
Advertisement

How do I get IDs associated with the most frequent value in PostgreSQL?

I have following data in my PostgreSQL 11 database count_tbl (Windows 10 x64 machine).

The following query, for each group (grp), finds the most frequent value:

The output of above query is:

Now, I would like to associate the most frequent value to the corresponding IDs (for example, for grp = 1, most frequent value 19.7 have ids 1, 2, 3, 4, 5, 6), let say, as an integer array. My expected output is:

Does someone care to reflect on this or suggest how this can be achieved?

Advertisement

Answer

You can use window functions and aggregation:

The inner query ranks records having the same grp by decreasing value. Then, the outer query filter on the top rows per froup and aggregates.


Edit: if you want the most occuring value per group (instead of the highest value) and its associated ids, then you can aggregate in the subquery instead:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement