June 11, 2008 at 9:09 am
I have records which contains id,name,MoveNumber which looks like below.
1, Fred, 10
2, Wilma, 10-1
3, Barney, 101-1
4, Pebbles, 10-2
5, Marsha, 10-7
6, Tom, 97
7, Bob, 97-3
If I order by MoveNumber, it is sorting it like a string like above. I would like to sort it so that it is numeric like below, is this possible?
10
10-1
10-2
10-7
97
97-3
101-1
thanks,
Mary
June 11, 2008 at 9:11 am
You'd have to convert things to numerics,stripping out the hyphens,for sorting purposes. Don't change the data, but extract the numbers (using CAST(SUBSTRING(CHARINDEX())) functions to get this.
June 11, 2008 at 11:25 am
mary_mormann (6/11/2008)
I have records which contains id,name,MoveNumber which looks like below.1, Fred, 10
2, Wilma, 10-1
3, Barney, 101-1
4, Pebbles, 10-2
5, Marsha, 10-7
6, Tom, 97
7, Bob, 97-3
If I order by MoveNumber, it is sorting it like a string like above. I would like to sort it so that it is numeric like below, is this possible?
10
10-1
10-2
10-7
97
97-3
101-1
thanks,
Mary
there may be more clever ways to accomplish your task. This is just one solution:
declare @t table ( id int,name varchar(20), MoveNumber varchar(20))
insert into @t (id,name,MoveNumber) values (1, 'Fred', '10')
insert into @t (id,name,MoveNumber) values (2, 'Wilma', '10-1')
insert into @t (id,name,MoveNumber) values (3, 'Barney', '101-1')
insert into @t (id,name,MoveNumber) values (4, 'Pebbles', '10-2')
insert into @t (id,name,MoveNumber) values (5, 'Marsha', '10-7')
insert into @t (id,name,MoveNumber) values (6, 'Tom', '97')
insert into @t (id,name,MoveNumber) values (7, 'Bob', '97-3')
select *
from @t
order by
(case when charindex('-',MoveNumber) = 0
then cast(MoveNumber as int)
else cast(Left(MoveNumber, charindex('-',MoveNumber)-1) as int) end),
(case when charindex('-',MoveNumber) = 0
then cast(0 as int)
else cast(Right(MoveNumber, charindex('-',reverse(MoveNumber))-1) as int) end)
* Noel
June 11, 2008 at 12:00 pm
This is exactly what I was looking for!
Thanks for your help.
Mary
June 11, 2008 at 1:26 pm
happy to help 🙂
* Noel
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply