Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get group number in postgresql?

I have a use case where I want to assign a unique increasing partition number to each partition when using a window query in postgres.

For example, I want to get an output like this:

Partition Key | Row_Num() | Partition Number  
Apple         | 1         | 1
Apple         | 2         | 1
Oranges       | 1         | 2
Oranges       | 2         | 2
Pear          | 1         | 3
Pear          | 2         | 3

Basically, apart from row_num() which gives us unique value within each "window", I want to have a number which is unique for each "window" How do I achieve this ? Is there any built in function in postgres for this ?

like image 907
Pratik Singhal Avatar asked Jun 04 '18 12:06

Pratik Singhal


People also ask

How do I use group by in PostgreSQL?

PostgreSQL GROUP BY. Last update on April 11 2019 11:34:26 (UTC/GMT +8 hours) The group by clause is used to divide the rows in a table into smaller groups that have the same values in the specified columns. This clause is used with a SELECT statement to combine a group of rows based on the values or a particular column or expression.

How to get row number in PostgreSQL?

Since PostgreSQL 8.4, you can easily show row number in PostgreSQL using ROW_NUMBER () function. Here’s the SQL query to get row id in PostgreSQL. In the above SQL query, we use row_number () window function to generate row number for each row. We also use over () to tell PostgreSQL to display row number for all rows without any ordering.

What is a grouping set in SQL?

A grouping set is a set of columns by which you group by using the GROUP BYclause. A grouping set is denoted by a comma-separated list of columns placed inside parentheses: (column1, column2, ...) For example, the following query uses the GROUP BYclause to return the number of products sold by brand and segment.

How do I get the number of employees in PostgreSQL?

PostgreSQL GROUP BY and ORDER BY. If we want to list the designation and the number of employees in each designation and show the result in ascending order of the number of employees from employee table, the following SQL can be used. The default order of ORDER BY is ascending. SQL.


2 Answers

You seem to want:

select partitionkey,
       row_number() over (partition by partitionkey order by partitionkey) as row_num,
       dense_rank() over (order by partitionkey) as partition_number
from t;
like image 199
Gordon Linoff Avatar answered Sep 29 '22 16:09

Gordon Linoff


You are looking for dense_rank()

. . .
dense_rank() over (order by PartitionKey) as number
like image 34
Yogesh Sharma Avatar answered Sep 29 '22 15:09

Yogesh Sharma