Here are some methods:
declare @t table(data varchar(15))
insert into @t
select '6134' union all
select '144' union all
select '7345' union all
select '109812' union all
select '100074'union all
select '1290' union all
select '45764'
--Method 1
select data from @t
order by cast(data as int)
--Method 2
select data from @t
order by data+0
--Method 3
select data from @t
order by len(data),data
--Method 4
select data from @t
order by replace(str(data),' ','0')
--Method 5
select data from @t
group by data
order by replicate('0',len(data)),data
--Method 6
select data from @t
order by replicate('0',(select max(len(data+0)) from @t)-len(data))+data
--Method 7
select data from @t
cross join
(
select len(max(data+0)) as ln from @t
) as t
order by replicate('0',ln-len(data))+data
(credit: sqlblogcasts.com/blogs/madhivanan)
Those method only can be used if the coloum containing number only.
For varchar also number, you can use this:
DECLARE @TBL TABLE
(
Name VARCHAR(100)
)
INSERT INTO @TBL VALUES('TKK1'),('TKK2'),('TKK11')
SELECT * FROM @TBL
ORDER BY LEN(Name),Name
This method only limited for fixed pattern (varchar value always same).
If you have data like this:
1
2
11
abc
you can use this method:
SELECT ... FROM table order by
CASE WHEN column < 'A' THEN LPAD(column, size, '0') ELSE column END;
declare @t table(data varchar(15))
insert into @t
select '6134' union all
select '144' union all
select '7345' union all
select '109812' union all
select '100074'union all
select '1290' union all
select '45764'
--Method 1
select data from @t
order by cast(data as int)
--Method 2
select data from @t
order by data+0
--Method 3
select data from @t
order by len(data),data
--Method 4
select data from @t
order by replace(str(data),' ','0')
--Method 5
select data from @t
group by data
order by replicate('0',len(data)),data
--Method 6
select data from @t
order by replicate('0',(select max(len(data+0)) from @t)-len(data))+data
--Method 7
select data from @t
cross join
(
select len(max(data+0)) as ln from @t
) as t
order by replicate('0',ln-len(data))+data
(credit: sqlblogcasts.com/blogs/madhivanan)
Those method only can be used if the coloum containing number only.
For varchar also number, you can use this:
DECLARE @TBL TABLE
(
Name VARCHAR(100)
)
INSERT INTO @TBL VALUES('TKK1'),('TKK2'),('TKK11')
SELECT * FROM @TBL
ORDER BY LEN(Name),Name
This method only limited for fixed pattern (varchar value always same).
If you have data like this:
1
2
11
abc
you can use this method:
SELECT ... FROM table order by
CASE WHEN column < 'A' THEN LPAD(column, size, '0') ELSE column END;
No comments:
Post a Comment