存储在varchar中的SQL Server混合数据类型中的自定义排序顺序

时间:2012-04-23 09:28:52

标签: sql-server sql-server-2008 sorting

我有这个

declare @testtable table (test nvarchar(max))


insert into @testtable (test) values ('1.2.3')
insert into @testtable (test) values ('1.20.3')
insert into @testtable (test) values ('1.19.x')
insert into @testtable (test) values ('1.x.x')
insert into @testtable (test) values ('1.19.3')
insert into @testtable (test) values ('DEC09')
insert into @testtable (test) values ('Plutonium')
insert into @testtable (test) values ('dec09')
insert into @testtable (test) values ('N/A')
insert into @testtable (test) values ('MyTest20')
insert into @testtable (test) values ('20MyTest')
insert into @testtable (test) values ('1.4.18')
insert into @testtable (test) values ('1.4.168')

select * from @testtable
order by test asc;

输出

1.19.3
1.19.x
1.2.3
1.20.3
1.4.168
1.4.18
1.x.x
20MyTest
DEC09
dec09
MyTest20
N/A
Plutonium

但我希望输出顺序为

1.2.3
1.4.18
1.4.168
1.19.3
1.19.x
1.20.3
1.x.x
20MyTest
DEC09
dec09
MyTest20
Plutonium
N/A

(注意N / A是“魔术”并且总是最大的,“版本”(ex 1.2.3)总是有3位数,尽管一个或多个数字可以是char x以表示“任何数字”,它应该总是被认为是最大可能的数字)

如何在SQL Server中完成此操作?

2 个答案:

答案 0 :(得分:3)

select TT.*
from @testtable as TT
order by case when TT.test = 'N/A' then 1 else 0 end,
         case when isnumeric(parsename(test, 3)+'E+00') = 1 then cast(parsename(test, 3) as int) else 99999 end,
         case when isnumeric(parsename(test, 2)+'E+00') = 1 then cast(parsename(test, 2) as int) else 99999 end,
         case when isnumeric(parsename(test, 1)+'E+00') = 1 then cast(parsename(test, 1) as int) else 99999 end,
         test

答案 1 :(得分:0)

这应该很容易。

创建一个包含2列的新表:

OrderValue string

描述字符串

按所需顺序放置值

a- 1.2.3

b- 1.4.18

c- 1.4.168

d- 1.19.3

e- 1.19.x

f- 1.20.3

g- 1.x.x

h- 20MyTest

i-DEC09

j-dec09

k- MyTest20

l-钚

m-N / A

现在使用这个新表加入testtable并按“OrderValue”

排序

就是这样