1

I have to sort a table by the version column which is a random string + numeric(x.xx.xx).For example my table looks like:

string 1.14.2
string 1.14.1
string 1.14
string 1.14.3
string 1.14.4
string 1.11
string 1.10
string 1.10.2
string 1.9
string 1.9.4
string 1.9.2
string 1.8
string 1.8.8
string 1.4.6

and my result has to look like:

string 1.14.4
string 1.14.3
string 1.14.2
string 1.14.1
string 1.11
string 1.10.2
string 1.10
string 1.9.4
string 1.9.2
string 1.9
string 1.8.8
string 1.8
string 1.4.6

my current sql is

SELECT * FROM t_plugins WHERE a_category = 'string' AND a_master_ig = 2
ORDER BY SUBSTRING_INDEX(SUBSTRING_INDEX(trim(a_name), " ", -1), ".", -1)```


3 Answers 3

1

Something like this should work:

order by
    cast(
        substring_index(
            substring_index(a_name, ' ', -1),
            '.', 
            1
         ) 
         as unsigned
    ) desc,
    cast(
        right(
            substring_index(a_name, ' ', -1),
            length(substring_index(a_name, ' ', -1)) 
                - locate('.', substring_index(a_name, ' ', -1))
        )
        as decimal(10, 5)
    ) desc

The idea is to :

  • separate the string from the version number

  • isolate the first digit of the version number (and cast it to an integer value) and use it as the first sort criteria

  • then isolate the second and third part, cast that to a decimal value, and use it as second sort criteria

Demo on DB Fiddle:

| a_name        |
| :------------ |
| string 1.14.4 |
| string 1.14.3 |
| string 1.14.2 |
| string 1.14.1 |
| string 1.14   |
| string 1.11   |
| string 1.10.2 |
| string 1.10   |
| string 1.9.4  |
| string 1.9.2  |
| string 1.9    |
| string 1.8.8  |
| string 1.8    |
| string 1.4.6  |
Sign up to request clarification or add additional context in comments.

Comments

0

I think this is simpler using implicit conversion:

order by substring_index(a_name, '.', 1) + 0,
         substring_index(substring_index(a.name, '.', 2), '.', -1) + 0,
         substring_index(a_name, '.', -1) + 0

Comments

0

Assuming there's no space within your "random string", this should give you the result you expect.

select 
    *
from 
    your_table
order by 
    cast('/' + TRIM(SUBSTRING(your_version_col,CHARINDEX(' ', your_version_col),LEN(your_version_col)))  + '/' as hierarchyid) desc

Comments

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.