我想订购带有两位小数/句号的值,并想知道是否有允许我这样做的CAST / Convert数据类型。值目前是这样的:
1.11.1
1.11.10
1.11.11
1.11.2
1.11.21
1.11.3
我希望他们按以下方式订购:
1.11.1
1.11.2
1.11.3
1.11.10
1.11.11
1.11.21
答案 0 :(得分:4)
也许是这样的
Declare @YourTable table (SomeField varchar(50))
Insert into @YourTable values
('1.11.1'),
('1.11.10'),
('1.11.11'),
('1.11.2'),
('1.11.21'),
('1.11.3')
Select A.*
From @YourTable A
Order By
cast(ParseName(SomeField,4) as int)
,cast(ParseName(SomeField,3) as int)
,cast(ParseName(SomeField,2) as int)
,cast(ParseName(SomeField,1) as int)
返回
SomeField
1.11.1
1.11.2
1.11.3
1.11.10
1.11.11
1.11.21
答案 1 :(得分:1)
您可以通过在CTE中拆分值然后订购来完成此操作...只需将#t替换为您的表,将c1替换为您的列名。
;with cte as(
select
c1,
LEFT(c1,CHARINDEX('.',c1) - 1) as LeftDigits,
SUBSTRING(c1,CHARINDEX('.',c1) + 1,LEN(c1) - CHARINDEX('.',c1) - CHARINDEX('.',reverse(c1))) as MiddleDigits,
RIGHT(c1,CHARINDEX('.',reverse(c1)) - 1) as RightDigits
from #t)
select * from cte
order by
LeftDigits,MiddleDigits,LEN(RightDigits),RightDigits
以下是每个人的一些测试数据
select '1.11.1' as C1 into #t
union all select
'1.11.10'
union all select
'1.11.11'
union all select
'1.11.2'
union all select
'1.11.21'
union all select
'1.11.3'
union all select
'2.11.1'
union all select
'2.1.1'
union all select
'2.2.1'
union all select
'33.0.5'
union all select
'2.01.11'
结果......
答案 2 :(得分:0)
您可以使用此查询,但它是围绕着
的方式select numbers
from #testdecimal
order by convert(int,substring(substring(numbers,charindex('.', numbers)+1, len(numbers)), charindex('.', substring(numbers,charindex('.', numbers)+1, len(numbers)))+1, len(numbers)))
创建表脚本:
create table #testdecimal
( numbers nvarchar(20)
)
insert into #testdecimal (numbers)
values
('1.11.1' ),('1.11.10' ),('1.11.11' )
,('1.11.2' ),('1.11.21' ),('1.11.3' )