ORDER BY in SQL

I have a type string column that contains values ​​in type strings:

1-1
1-5
1-14
1-7
1-3

Now, if I use ORDER BY in this column, I get the following order:

1-1
1-14
1-3
1-5
1-7

What will be the right way to order it as 1-1, 1-3, 1-5,1-7,1-14

thank you for your time

+3
source share
8 answers

You can rename "1-1" to "1-01"

+7
source

Assuming your first character can also change:

order by convert(substr(my_field, 1, locate(my_field, '-') - 1) as int),
         convert(substr(my_field, locate(my_field, '-') + 1) as int)
+10
source

- .

+5

:

SELECT *  FROM
(
SELECT '1-1' Id
UNION
SELECT '1-5' Id
UNION
SELECT '1-14' Id
UNION
SELECT '1-7' Id
UNION
SELECT '1-3' Id
) a
ORDER BY CAST(REPLACE(Id, '-', '') AS UNSIGNED)
+2

?

, .

+1

- , , . .

"" ( ), , , , :

1-5 1000 + 5 = 1005 1-14 1000 + 14 = 1014

. . , .

+1

- ( doesn-t metter)

CAST (SUBSTRING (, CHARINDEX (, '-', 0) +1, LEN () +1) int)

, ..

0
SELECT  *
FROM    (
        SELECT '1-1' Id
        UNION ALL
        SELECT '1-5' Id
        UNION ALL
        SELECT '1-14' Id
        UNION ALL
        SELECT '1-7' Id
        UNION ALL
        SELECT '1-3' Id
        UNION ALL
        SELECT '10-4' Id
        ) a
ORDER BY
        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(id, '-', -2), '-', 1) AS UNSIGNED),
        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(id, '-', -1), '-', 1) AS UNSIGNED)
0
source

Source: https://habr.com/ru/post/1785455/


All Articles