'Sql Server query varchar data sort like int
I have one table like
CREATE TABLE table_name
(
P_Id int,
amount varchar(50)
)
Data Like
Id amount
----------
1 2340
2 4568
3 10000
Now I want to sort table by amount but one problem is amount is varchar so it sort table like this
Id amount
----------
3 10000
1 2340
2 4568
but i want result like this
Id amount
----------
3 10000
2 4568
1 2340
what should i do ?
Solution 1:[1]
Cast amount column into Numeric in ORDER BY
clause while selecting:
SELECT * FROM MyTable
ORDER BY CAST(amount AS Numeric(10,0)) DESC
You can change the decimal point value according to your requirement to get more precise result:
SELECT * FROM MyTable
ORDER BY CAST(amount AS Numeric(10,2)) DESC
^
Result:
Id | amount |
---|---|
3 | 10000 |
2 | 4568 |
1 | 2340 |
See this dbfiddle
Note: As @Ice suggested, this will fail if the amount field contains non numeric data like ab123
or xyz
(obviously).
Solution 2:[2]
Solution 3:[3]
Try this
SELECT *
FROM #varchar_field
ORDER BY
CASE
WHEN ISNUMERIC(mixed_field) = 1 THEN CAST(mixed_field AS FLOAT)
WHEN ISNUMERIC(LEFT(mixed_field,1)) = 0 THEN ASCII(LEFT(LOWER(mixed_field),1))
ELSE 2147483647
END
Ref: http://sqlserverplanet.com/tsql/how-to-order-numeric-values-in-a-varchar-field
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | hesham.shabana |