简体   繁体   中英

Jsonb data postgresql count distinct values

I have PostgreSQL 11.5 with something similar to this jsonb data:

[{"name":"$.publishedTitle", "value":"Code"},{"name":"$.publishedYear","value":"1972"}]
[{"name":"$.publishedTitle", "value":"Test"},{"name":"$.publishedYear","value":"2020"}]
[{"name":"$.publishedTitle", "value":"Code"},{"name":"$.publishedYear","value":"2019"}]

My desired result is (how many times a title is published

title publishedYearCount
Code 2
Test 1

I have tried this:

SELECT distinct(b.field_value) AS publishedYearCount, COUNT(*)
  FROM (SELECT *
          FROM (SELECT (jsonb_array_elements(result) ::jsonb) - >> 'name' field_name,
                       (jsonb_array_elements(result) ::jsonb) - >> 'value' field_value,
                  FROM books
                 WHERE bookstore_id = '3') a
         WHERE a.field_name in ('$.publishedTitle', '$.publishedYear')) b
 GROUP BY b.field_value

I understand that you want the count of distinct years per published title.

You could unnest each array in a lateral join, and pivot to put the year and title on the same row; then we can just aggregate and count in the outer query:

select x.ptitle, count(distinct x.pyear) cnt_years
from books b
cross join lateral (
    select 
        max(j.elt ->> 'value') filter(where j.elt ->> 'name' = '$.publishedTitle') ptitle,
        max(j.elt ->> 'value') filter(where j.elt ->> 'name' = '$.publishedYear' ) pyear,
    from jsonb_array_elements(b.result) j(elt)
) x
where b.bookstore_id = '3'
group by x.ptitle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM