我有一个nvarchar
列,当我选择使用以下查询时,它会给出以下输出 -
SELECT DISTINCT [VERSION]
FROM IMPORT.BUDGETIMPORT
WHERE VERSION LIKE 'Test'+'18'+'%'
ORDER BY [VERSION] ASC
输出:
Test18
Test18.1
Test18.10
Test18.2
Test18.3
Test18.4
Test18.5
Test18.6
我想在选择 -
时按编号订购Test18
Test18.1
Test18.2
Test18.3
Test18.4
Test18.5
Test18.6
Test18.10
我怎么能只根据数字排序。
答案 0 :(得分:3)
试试这个。
首先按字符串的长度排序,然后按字符串本身排序。
<强>查询强>
SELECT [VERSION]
FROM IMPORT.BUDGETIMPORT
WHERE [VERSION] LIKE 'Test18'+'%'
GROUP BY [VERSION]
ORDER BY LEN([VERSION]), [VERSION];
<强> demo 强>
答案 1 :(得分:0)
对于数值数据类型,18.1与18.10相同 对于字符串数据类型,18.10将在18.2之前出现
尝试使用以下方法获得预期结果
declare @t table
(
[version] nvarchar(50)
)
insert into @t
values('Test18'),
('Test18.1'),
('Test18.10'),
('Test18.2'),
('Test18.3'),
('Test18.4'),
('Test18.5'),
('Test18.2'),
('Test18.3'),
('Test18.4'),
('Test18.5'),
('Test18.6')
;with cte
as
(
select
rn = ROW_NUMBER() OVER(PARTITION BY [VERSION] ORDER BY [VERSION]),
ln = LEN([VERSION]),
[version]
from @t
)
select
*
from cte
WHERE rn = 1
order by ln
答案 2 :(得分:0)
执行此操作的另一个选项是将版本转换为float
;
SELECT DISTINCT [VERSION], cast(SUBSTRING([VERSION], 5, 10) as float) as VersionAsFloat
FROM IMPORT.BUDGETIMPORT
WHERE VERSION LIKE 'Test'+'18'+'%'
ORDER BY VersionAsFloat ASC