简体   繁体   中英

Postgres aggregation function for jsonb

i want to aggregate postgres data, but i need where one query where i can use aggregate function for different datatype . Basically want to combine this two queries.

select browser_id, jsonb_object_agg(key, val)
from (
    select browser_id, key, sum(value::numeric) val
    from aggregated_browser_days, jsonb_each_text(geo_city)
    group by browser_id, key
    ) s
group by browser_id;

select browser_id, sum(pageviews) as total_pageviews,
       STRING_AGG(DISTINCT browser_family, ',') AS browser, 
       STRING_AGG(DISTINCT device_model, ',') AS device_model,
       SUM(timespent) as total_timespent, SUM(sessions) as session_count
from data
GROUP BY browser_id

Can anyone please guide me?? Thanks in advance

This data is coming from two different tables. So a JOIN seems like the right approach. Just in case the base tables contain different sets of browsers, I am suggesting a FULL JOIN :

select *
from (select browser_id, jsonb_object_agg(key, val)
      from (select browser_id, key, sum(value::numeric) as val
            from aggregated_browser_days cross join lateral
                 jsonb_each_text(geo_city)
            group by browser_id, key
           ) s
      group by browser_id
     ) bd full join
     (select browser_id, sum(pageviews) as total_pageviews,
             STRING_AGG(DISTINCT browser_family, ',') AS browser, 
             STRING_AGG(DISTINCT device_model, ',') AS device_model,
             SUM(timespent) as total_timespent, SUM(sessions) as session_count
      from data
      group by browser_id
     ) b
     using (browser_id)

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