May 14, 2015 at 12:35 pm
Hello everyone,
I need help to sort a column having alpha numberic values
000000000000001
000000000000005
000000000000006
00000000000002N
00000000000002S
0002
12-I395
14-I395
9-I395
AL001
AL002
MD0001
MD0002
MD0003
VA0001
VA0002
Please advice , how do I do it?
Thanks
Kapil
May 14, 2015 at 12:39 pm
ORDER BY <column name>
Add DESC at the end if you want to sort in descending order
-- Itzik Ben-Gan 2001
May 14, 2015 at 12:41 pm
they are already sortable varchar values, so how do you want to sort them differently than the natural order by text via ORDER BY [ColumnName]?
the order you pasted them is already sorted.
;WITH MyCTE([ColumnName])
AS
(
SELECT '000000000000001' UNION ALL
SELECT '000000000000005' UNION ALL
SELECT '000000000000006' UNION ALL
SELECT '00000000000002N' UNION ALL
SELECT '00000000000002S' UNION ALL
SELECT '0002' UNION ALL
SELECT '12-I395' UNION ALL
SELECT '14-I395' UNION ALL
SELECT '9-I395' UNION ALL
SELECT 'AL001' UNION ALL
SELECT 'AL002' UNION ALL
SELECT 'MD0001' UNION ALL
SELECT 'MD0002' UNION ALL
SELECT 'MD0003' UNION ALL
SELECT 'VA0001' UNION ALL
SELECT 'VA0002'
)
SELECT * FROM MyCTE ORDER BY [ColumnName]
Lowell
May 14, 2015 at 12:56 pm
Thanks , It works
May 14, 2015 at 1:39 pm
Just to pile on a bit, use the desired collation to get the desired sort order
😎
Collation example with Lowell's data sample:
use tempdb;
go
;WITH MyCTE([ColumnName])
AS
(
SELECT N'000000000000001' UNION ALL
SELECT N'000000000000005' UNION ALL
SELECT N'000000000000006' UNION ALL
SELECT N'00000000000002N' UNION ALL
SELECT N'00000000000002S' UNION ALL
SELECT N'0002' UNION ALL
SELECT N'12-I395' UNION ALL
SELECT N'14-I395' UNION ALL
SELECT N'9-I395' UNION ALL
SELECT N'AL001' UNION ALL
SELECT N'AL002' UNION ALL
SELECT N'MD0001' UNION ALL
SELECT N'MD0002' UNION ALL
SELECT N'MD0003' UNION ALL
SELECT N'VA0001' UNION ALL
SELECT N'VA0002'
)
SELECT [ColumnName] COLLATE Arabic_100_BIN FROM MyCTE ORDER BY [ColumnName];
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply