Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add numbers to grouped rows in postgresql group by clause

I have a PostgreSQL table, containing duplicate values in a text column. It looks like this:

gid, capt
1, foo
2, foo
3, bar
4, bar
5, bar
6, buz
7, buz

I need to add a column with distinct numbers for each value in a group, so my table should look like this:

gid, capt, rnum
1, foo, 1
2, foo, 2
3, bar, 1
4, bar, 2
5, bar, 3
6, buz, 1
7, buz, 2

It's a kind of a row number inside each group, always starting from 1. Can anyone please provide me with an appropriate SELECT statement?

like image 814
mofoyoda Avatar asked May 27 '15 19:05

mofoyoda


People also ask

How do I add row numbers in PostgreSQL?

In PostgreSQL, the ROW_NUMBER() function is used to assign a unique integer to every row that is returned by a query. Syntax: ROW_NUMBER() OVER( [PARTITION BY column_1, column_2, …] [ORDER BY column_3, column_4, …] )

What is GROUP BY clause in PostgreSQL?

The PostgreSQL GROUP BY clause is used to divide rows returned by SELECT statement into different groups. The speciality of GROUP BY clause is that one can use Functions like SUM() to calculate the sum of items or COUNT() to get the total number of items in the groups.

Can we use GROUP BY without count?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.

Can I have GROUP BY and order by together in SQL query?

Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.


2 Answers

With help from this question and its answers:

SELECT gid, capt, row_number() OVER (PARTITION BY capt ORDER BY gid) AS rnum
FROM your_table_here ORDER BY gid;

The row_number window function provides the count.

The PARTITION BY statement in the OVER clause tells the database to restart its numbering with each change to capt. The ORDER BY in the OVER clause tells the database to count along with the gid column.

like image 164
Politank-Z Avatar answered Oct 17 '22 23:10

Politank-Z


This can be done using window functions:

select gid, 
       capt, 
       row_number() over (partition by capt order by gid) as rnum
from the_table
order by capt, gid;
like image 20
a_horse_with_no_name Avatar answered Oct 17 '22 23:10

a_horse_with_no_name