我有一张像
这样的表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
我该怎么办?
答案 0 :(得分:19)
在ORDER BY
子句中将数量列转换为数字,同时选择:
SELECT * FROM MyTable
ORDER BY CAST(amount AS Numeric(10,0)) DESC
结果:
╔════╦════════╗
║ ID ║ AMOUNT ║
╠════╬════════╣
║ 3 ║ 10000 ║
║ 2 ║ 4568 ║
║ 1 ║ 2340 ║
╚════╩════════╝
答案 1 :(得分:11)
答案 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