Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a sequence number for each element in a group using an Oracle SQL query

I have an Oracle table with the following data:

ID          VALUE
10           A
10           B
10           C
20           A1
30           C1
30           D1

I want to do a group by based on the ID column and print a new column with the sequence number within each group.

The output would look like this:

ID          VALUE     GROUPSEQ
10           A           1
10           B           2
10           C           3
20           A1          1
30           C1          1
30           D1          2

Can this be done using an Oracle SQL query, without creating a temporary table?

like image 354
Victor Avatar asked Sep 01 '15 14:09

Victor


People also ask

How do I add a sequence number in Oracle query?

The syntax to create a sequence in Oracle is: CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value; sequence_name. The name of the sequence that you wish to create.

How do I create a sequence number in SQL group?

The Rank function can be used to generate a sequential number for each row or to give a rank based on specific criteria. The ranking function returns a ranking value for each row. However, based on criteria more than one row can get the same rank.

How do I create a sequence in Oracle SQL Developer?

To create a sequence in another user's schema, you must have the CREATE ANY SEQUENCE system privilege. Specify the schema to contain the sequence. If you omit schema , then Oracle Database creates the sequence in your own schema. Specify the name of the sequence to be created.


1 Answers

You need ROW_NUMBER

SELECT ID, VALUE, row_number() OVER (PARTITION BY ID ORDER BY value) GROUPSEQ
FROM myTable
like image 164
Juan Carlos Oropeza Avatar answered Nov 15 '22 19:11

Juan Carlos Oropeza