Sql Server查询varchar数据排序类似于int

时间:2013-05-30 06:46:18

标签: sql sql-server sql-order-by

我有一张像

这样的表
CREATE TABLE table_name
(
P_Id int,
amount varchar(50)
)

数据类似

Id amount
----------
1 2340
2 4568
3 10000

现在我想按数量对表进行排序,但是一个问题是数量是varchar所以它像这样排序表

Id amount
----------
3 10000
1 2340
2 4568

但我想要这样的结果

Id amount
----------
3 10000
2 4568
1 2340

我该怎么办?

3 个答案:

答案 0 :(得分:19)

ORDER BY子句中将数量列转换为数字,同时选择:

SELECT * FROM MyTable
ORDER BY CAST(amount AS Numeric(10,0)) DESC

结果:

╔════╦════════╗
║ ID ║ AMOUNT ║
╠════╬════════╣
║  3 ║  10000 ║
║  2 ║   4568 ║
║  1 ║   2340 ║
╚════╩════════╝

请参阅this SQLFiddle

答案 1 :(得分:11)

尝试ABS():

SELECT * FROM MyTable ORDER BY ABS(MyCol) DESC;

<强> SQL Fiddle

答案 2 :(得分:0)

试试这个

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

参考:http://sqlserverplanet.com/tsql/how-to-order-numeric-values-in-a-varchar-field