Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
Postgres: How to get aggregates of multiple columns

I want to implement filtered navigation with postgres, but I'm not sure how to return the count of each value in multiple fields from the result set.

Example Schema:

id, name, status

for this query i'd want to see something like (doesn't have to mimic this structure):

name: [(Bob, 20), (Joe, 15), (Sue, 5)]
status[(active, 15), (inactive, 25)]
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Check Grouping Sets

with t (name, status) as (values
    ('Bob', 'active'),('Bob', 'active'),
    ('Joe', 'inactive'),('Joe', 'active'),('Joe', 'active')
)
select json_object_agg(case g when 1 then 'name' else 'status' end,a)
from (
    select jsonb_agg(jsonb_build_object(coalesce(name,status), total)) as a, g
    from (
        select name, status, count(*) as total, grouping(name,status) as g
        from t
        group by grouping sets ((name),(status))
    ) s
    group by g
) s
;
                                  json_object_agg                                   
------------------------------------------------------------------------------------
 { "name" : [{"Bob": 2}, {"Joe": 3}], "status" : [{"active": 4}, {"inactive": 1}] }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!