简体   繁体   中英

SQL sorting by a column that is a String

I am trying to write a query that will sort a column by the number that it is. However, the column is a string, so instead of sorting like 1, 2, 3, it will sort 1, 10, 11, 12, etc. Is there a way to change a column from a string to a number, or even a way to change how it orders the Strings. Here is my code and its output:

SELECT DISTINCT draft_number
    FROM NBA_data.dbo.all_seasons
        WHERE draft_year = '2016'
        ORDER BY draft_number;

Output:

draft_number
1
10
11
18
19
2
20
21

Just cast draft_number to datatype INT in Order By clause.

ORDER BY CAST(draft_number As INT);

Use ALTER TABLE to change the column type from string to number. Thus you don't have the hassle with every query on that column. Always use the appropriate data type for your data.

ALTER TABLE NBA_data.all_seasons ALTER COLUMN draft_number INT; 

Demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=23324061a0c49d61a0172d46ad74bb77

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM