Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query - Order by String (which contains number and chars)

Tags:

sql

sql-server

I need some help with a sql query which I can't get it work. I need to order these values by number then by letter.

Any suggestion how to do it?

I am working on Sql Server 2014, but I think it's irrelevant.

Cod_Turma   Turma
1           11-A
2           11-F
3           10-F
4           11-G
5           11-I
6           10-E
7           12-L
8           10-J
9           7-B
10          9-B
11          7-E
12          7-D
13          12-H

Output should be:

Cod_Turma   Turma
9           7-B
12          7-D
11          7-E
10          9-B
...
like image 800
Exprove Avatar asked Nov 27 '25 01:11

Exprove


1 Answers

Possible solution:

SELECT * FROM TableName 
ORDER BY CAST(LEFT(Turma, CHARINDEX('-', Turma) - 1) AS INT), --left part
         SUBSTRING(Turma, CHARINDEX('-', turma), LEN(turma))  --right part
like image 110
Giorgi Nakeuri Avatar answered Nov 29 '25 19:11

Giorgi Nakeuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!