Querying combinations of JSON returns odd results

ぃ、小莉子 提交于 2019-12-08 05:12:29

A kind person from Postgresql's IRC channel helped find the answer and craft the correct query. The credit is actually his, not mine.

He helped realize that the albums and srcs should be added to arrays for comparison. For instance:

SELECT array_agg(rep_id), count(*) AS ct
FROM (SELECT rep_id, 
             data->>'background' as background, 
             array_agg(o->>'album' order by o->>'album') as albums, 
             array_agg(o->>'src' order by o->>'album') as srcs  
           FROM reports r, 
           json_array_elements(r.data->'objects') o 
           GROUP BY rep_id) s 
GROUP BY background, albums, srcs
ORDER BY count(*) DESC
LIMIT 5;

I don't know if this is the best way of doing it but it works. Suggestions are welcome.

First of all, you have a typo, change 'scr' to 'src'. But your query is correct, just take a look at your query without grouping:

select
     r.rep_id, r.data->>'background' as background, o->>'album' as album, o->>'src' as src
from reports r, json_array_elements(r.data->'objects') o;

------------------------------------------------------------
REP_ID  BACKGROUND      ALBUM   SRC
1       background.png      1   fooA.png
1       background.png      2   barB.png
2       background.png      2   barB.png
2       background.png      2   barB.png

If you count distinct on rep_id you will get the number of rows where a unique combination occurred.

SELECT distinct array_agg(distinct r.rep_id) AS ids, count(distinct r.rep_id) AS ct, array[r.data->>'background', o->>'album', o->>'src'] as combination
FROM   reports r
  , json_array_elements(r.data->'objects') o
GROUP  BY r.data->>'background'
   , o->>'album'
   , o->>'src'
ORDER  BY 2 DESC

Result on first dataset:

ids     ct  combination
{1,2,3} 3   {background.png,1,fooA.png}
{1,3}   2   {background.png,2,barB.png}
{2}     1   {background.png,2,barC.png}
{4}     1   {backgroundA.png,1,fooA.png}
{4}     1   {backgroundA.png,3,barB.png}

Reult on second dataset:

ids     ct  combination
{1,2}   2   {background.png,2,barB.png}
{1}     1   {background.png,1,fooA.png}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!