Custom Sorting on Alpha Numeric Column



create table #t (col varchar(100))

insert into #t values ('10 x 5.5 x 2')
insert into #t values ('125 x 95 x 13.5/21')
insert into #t values ('1264.01 x 1200 x 22.23')
insert into #t values ('130 x 105 x 12')
insert into #t values ('130 x 95 x 12') --added
insert into #t values ('210 x 180 x 15')
insert into #t values ('28 x 16 x 15.2')
insert into #t values ('28 x 16.8 x 6/7.5')
insert into #t values ('52 x 25 x 10')
insert into #t values ('52 x 25 x 7/7.5')
insert into #t values ('52/58 x 25 x 7')
insert into #t values ('52/59 x 25 x 10/15.5')
insert into #t values ('55/61 x 35 x 11.5/16')
insert into #t values ('74.2/78.2 x 56 x 8/10.5')
insert into #t values ('74.5/79.5 x 45/42.5 x 12/13.')

 

;with mycte as (
select col,
parsename(Replace(replace(col,'.','*'),'X','.'),3) col1
,parsename(Replace(replace(col,'.','*'),'X','.'),2) col2
,parsename(Replace(replace(col,'.','*'),'X','.'),1) col3  from #t)

,mycte1 as (
Select col,
 Cast(ISNULL(Replace(parsename(Replace(col1,'/','.'),2),'*','.'), Replace(parsename(Replace(col1,'/','.'),1),'*','.')) as Decimal(6,2)) col11
 , Cast(Replace(parsename(Replace(col1,'/','.'),1),'*','.') as Decimal(6,2)) as col12
 , Cast(ISNULL(Replace(parsename(Replace(col2,'/','.'),2),'*','.'), Replace(parsename(Replace(col2,'/','.'),1),'*','.')) as Decimal(6,2)) col21
 , Cast(Replace(parsename(Replace(col2,'/','.'),1),'*','.') as Decimal(6,2)) as col22
 , Cast(ISNULL(Replace(parsename(Replace(col3,'/','.'),2),'*','.'), Replace(parsename(Replace(col3,'/','.'),1),'*','.')) as Decimal(6,2)) col31
 , Cast(Replace(parsename(Replace(col3,'/','.'),1),'*','.') as Decimal(6,2)) as col32 

from  mycte )

Select col from mycte1
Order by col11,col12,col21,col22,col31,col32

 

drop table #t



 

https://social.msdn.microsoft.com/Forums/en-US/242efaf7-7aaa-46e6-a537-1fbd9666abe9/how-to-sort-the-alpha-numeric-character-into-number?forum=transactsql

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s