Question

I have a dataset like so:

print_id
--------
2b
1
2
4b
4a
3
6
2a
5

The print ID can be in the format of: /([0-9]+)([a-e]{1})?/

What I want to is order them first by number, and by letter if there is any. If there is no letter, then it's the first in the order for that number. So the result should be like so:

print_id
--------
1
2
2a
2b
3
4a
4b
5
6

I tried ORDER BY (print_id + 0) it sorts the numbers correctly but it just doesn't quite do the trick. Any suggestions?

Was it helpful?

Solution

You can have multiple expressions in the ORDER BY clause:

ORDER BY print_id + 0, print_id

This will first try to order them numerically (discarding the letter suffix), and if they are numerically equivalent, it will order them by their string values (including the letter suffix). For the rule that you described, the only time this will break is if you have leading zeroes; for example, this ORDER BY clause will sort '01b' above '1a'. Can that happen in your data?

OTHER TIPS

ORDER BY print_id

should do what you want. It will order by the character field print_id, which is equivalent to ordering by individual characters.

So, for a table

print_id
--------
1
3a
3c
2b
2c
2a
3b
0
0b
00

You'll get

print_id
--------
0
00
0b
1
2a
2b
2c
3a
3b
3c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top