13

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?

1
  • 2
    Why you have tagged this ques with mysql and oracle both. Please remove mysql. Commented Sep 1, 2015 at 15:11

3 Answers 3

24

You need ROW_NUMBER

SELECT ID, VALUE, row_number() OVER (PARTITION BY ID ORDER BY value) GROUPSEQ
FROM myTable
Sign up to request clarification or add additional context in comments.

1 Comment

Great !! It Worked. Thx
2

You can try this:-

 SELECT ID, VALUE, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY VALUE) "GROUPSEQ"
 FROM YOUR_TABLE;

2 Comments

Any specific reason this answer should be accepted over the other one which same and was given 3 minutes earlier than you?
I was saying because user doesn't select any of the answer as selected. If user selects other one. Then also i dont have any problem. Because selecting the answer help other people in future as well.
1

I have written a query for you. I hope it will solve your problem :

(SELECT t.*,
    ROW_NUMBER ()
    OVER (PARTITION BY t.id
          ORDER BY t.id)
       seq_no
  FROM test t);

Check Fiddle

5 Comments

I think you want ORDER BY t.value
No it should be order t.id
if you order by t.id first group have 10 three time, so no really order
what if the data into table is unordered
You can see the OP result is order by value. if you order by id you can have any random result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.