SQL Server : sorting letters with number -


i'm not @ sql - below have tried far searching. can see in picture barangayname not in order. can see there 'z , s, , 1' between letter b , brgy 10 , brgy 11 far each other.

enter image description here

select *  dbo.barangay order substring(a.barangayname, patindex('%[0-9]%', a.barangayname), len(a.barangayname)) 

i tried work out you.

let's take following sample data:

declare @table table(id int,name varchar(100)) insert @table values(134,'brgy 1') insert @table values(256,'brgy 100') insert @table values(687,'sample 1 z1') insert @table values(954,'brgy 11 zn9') insert @table values(887,'brgy 10 zn11') insert @table values(785,'brgy 098 xys') insert @table values(785,'zone 2 wer') 

the following select statement:

select * @table order 2 

will result as:

enter image description here

but using following code, custom sorting you,

;with cte as(     select *,     substring(name, 0, charindex(' ', name)) spart,     ltrim(rtrim(substring(name, patindex('%[0-9]%', name), len(name))))+' ' restpart     @table ) select id, name cte  order      spart,     cast(left(restpart, patindex('%[^0-9]%', restpart)) int); 

you can achieve:

enter image description here

does make sense?

edit to fix conversion issue

to avoid conversion issue, replace order by section following:

order      spart,     case         when isnumeric(left(restpart, patindex('%[^0-9]%', restpart)))=1 cast(left(restpart, patindex('%[^0-9]%', restpart)) int)         else 0     end; 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -