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 ?
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.
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.
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.
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.
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;
You are looking for dense_rank()
. . .
dense_rank() over (order by PartitionKey) as number
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