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

276
Views
Postgres COUNT instances and put in "buckets"

I have a big table with row that each have a location id (location_id). Down the location_id column there are multiple instances of the same value. What I want to do is count how many times each value appears and then place that value into a "bucket"

I tried this, but ended up with everything in the "500+" bucket.

SELECT
 CASE WHEN count(location_id) > 1 AND count(location_id) <= 25 THEN '1-25'
 WHEN count(location_id) > 25 AND count(location_id) <= 500 THEN '26-500'
 WHEN count(location_id) > 500  THEN '500+'
 ELSE 'nothing'
 end as bucket,
 count(*) as Column1
FROM myTable

What am I doing wrong here?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You want two levels of aggregation:

SELECT (CASE WHEN cnt <= 25 THEN '1-25'
             WHEN cnt <= 500 THEN '26-500'
             ELSE '500+'
        END) as bucket, COUNT(*) as numlocations, SUM(cnt) as numTotal
FROM (SELECT location_id, count(*) as cnt
      FROM myTable
      GROUP BY location_id
     ) l
GROUP BY bucket
ORDER BY MIN(cnt);
over 4 years ago · Santiago Trujillo Report

0

Try this:-

    Select 
     CASE WHEN #_cnt >= 1 AND #_cnt<= 25 THEN '1-25'
     WHEN #_cnt > 25 AND #_cnt <= 500 THEN '26-500'
     WHEN #_cnt > 500  THEN '500+'
     ELSE 'nothing'
     end as bucket,
   count(*) as column1
    from
    (
    Select location_id, count(*) as #_cnt
    from
    myTable
    group by location_id
    ) a
group by bucket

Thanks:-)

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!