表1
id value
---------
1 100
2A 200
2 300
10 500
8 200
....
Select *
from table1
order by id
将输出显示为
id value
------------
1 100
10 500
2A 200
2 300
8 200
....
如何正确订购?
预期输出
id value
----------
1 100
2 300
2A 200
8 200
10 500
....
答案 0 :(得分:1)
如果修复了最后一个字符可能是字符,那么您可以尝试以下查询
WITH A(ID)
AS
(
SELECT '1'
UNION ALL
SELECT '2C'
UNION ALL
SELECT '2A'
UNION ALL
SELECT '2'
UNION ALL
SELECT '10'
)
SELECT *
FROM A
ORDER BY
convert(int,
Case When IsNumeric(ID) = 0 then left(ID,len(id)-1)
Else ID END
) , Case When IsNumeric(ID) = 0 then RIGHT(ID,1) Else '0' END
如果它是可变的,那么你可以编写一个用chamlter替换其ansi值或0的函数。然后关闭该栏目。
答案 1 :(得分:0)
SELECT
LEFT(ID,1),
RIGHT(ID,1),
*
FROM table1
ORDER BY LEFT(ID,1),RIGHT(ID,1)
应该这样做,我甚至不确定所选语句中是否需要左右。
答案 2 :(得分:0)
Select *
from table1
order by cast(replace(lower(id), 'abcdefg', '') as int),
replace(id, '0123456789','');
答案 3 :(得分:0)
SELECT * FROM table1 ORDER BY CAST(id as varchar(50))
答案 4 :(得分:0)
CREATE FUNCTION [dbo].[RemoveNonAlphaCharacters](@Temp varchar(1000))
RETURNS int
AS
BEGIN
WHILE PatIndex ('%[^0-9]%', @Temp) > 0
SET @Temp = Stuff( @Temp, PatIndex('%[^0-9]%' , @Temp ), 1, '')
RETURN @Temp
END
SELECT id, value
FROM dbo.Table1
ORDER BY [dbo].[RemoveNonAlphaCharacters](id) ASC