Reputation: 499
I have a nvarchar
column and when I am selecting using below query this it is giving below output -
SELECT DISTINCT [VERSION]
FROM IMPORT.BUDGETIMPORT
WHERE VERSION LIKE 'Test'+'18'+'%'
ORDER BY [VERSION] ASC
Output:
Test18
Test18.1
Test18.10
Test18.2
Test18.3
Test18.4
Test18.5
Test18.6
I want to order it by number while selecting -
Test18
Test18.1
Test18.2
Test18.3
Test18.4
Test18.5
Test18.6
Test18.10
How could I sorted based on number only.
Upvotes: 2
Views: 62
Reputation: 13146
Another option to perform it is casting the version as 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
Upvotes: 0
Reputation: 86
Try this one.
Order first by length of the string and then by the string itself.
Query
SELECT [VERSION]
FROM IMPORT.BUDGETIMPORT
WHERE [VERSION] LIKE 'Test18'+'%'
GROUP BY [VERSION]
ORDER BY LEN([VERSION]), [VERSION];
Upvotes: 3
Reputation: 8043
For numeric Datatypes, 18.1 is same as 18.10 and for string datatypes, 18.10 will come before 18.2
Try the below method to get your expected result
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
Upvotes: 0