cantelopehead
cantelopehead

Reputation: 13

SQL ORDER BY a sequence column then all records in group, then resume next sequence

I have these two columns in a table (SEQ, GROUP_CODE) with the following data (example):

SEQ, GROUP_CODE
---------------    
1, 2
2, 2
3, 2
4, 5
5, 2
6, 3
7, 5

I need this to sort like this:

SEQ, GROUP_CODE
---------------    
1, 2
2, 2
3, 2
5, 2
4, 5
7, 5
6, 3

Basically, use the sequence to start the ordering and "drain" all group records before moving on to the next sequence before draining its group and so on. I know I could do this with a stored procedure using a cursor, but would like to see if this can be done with an ORDER BY.

Upvotes: 1

Views: 79

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269693

You can use window functions in order by. So:

order by min(seq) over (partition by group_code),
      seq

Upvotes: 3

Related Questions