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?
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, …] )
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With