Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional group by (group similar items) in PostgreSQL

I have the following query:

SELECT s.id,
       s.name,
       s.prom,
       s.some_other_field,
       ... many more fields also
FROM mytable s
INNER JOIN (on some other tables etc.)

In the case where there are more than 6 records with the same name (s.name), I want to group these items together as one row (I don't care which other data is grouped into that row, i.e. the first record of that group would be fine).

Is this possible in Postgres? I guess it is a conditional group by in a sense that I want to group the records where the same name appears more than 6 times, whilst returning all the other records as normal.

Any help is much appreciated - thanks!

like image 771
harman_kardon Avatar asked Jan 11 '12 09:01

harman_kardon


People also ask

How to use SUM and GROUP BY in PostgreSQL?

Introduction to PostgreSQL GROUP BY clause The GROUP BY clause divides the rows returned from the SELECT statement into groups. For each group, you can apply an aggregate function e.g., SUM() to calculate the sum of items or COUNT() to get the number of items in the groups.

Why use GROUP BY in PostgreSQL?

The PostgreSQL GROUP BY clause is used in collaboration with the SELECT statement to group together those rows in a table that have identical data. This is done to eliminate redundancy in the output and/or compute aggregates that apply to these groups.


1 Answers

you can do this:

select * from (

    SELECT s.id,
           s.name,
           s.prom,
           s.some_other_field,
           ... many more fields also,
           row_number() over (partition by s.name order by s.id) as rnk,
           count(*) over (partition by s.name) cnt
    FROM mytable s
    INNER JOIN (on some other tables etc.)

) a
where cnt < 6 or (cnt >=6 and rnk = 1)
like image 149
Florin stands with Ukraine Avatar answered Oct 31 '22 03:10

Florin stands with Ukraine