Solved

ORDER BY a Column with Numeric Values

Posted on 2006-11-06
6
269 Views
Last Modified: 2008-01-09
I have a column that stores suite/apartment numbers. This is data that is imported to our local database, so I don't have control over validating the data. The data that the column holds sometimes is a number, text, or a combination of the two, such as "201", "12A", or "SUITE 220".

Is there any way to have this ordered numerically, when appropriate, such as:

1,2,3,11,24, instead of 1,11,2,24,3
12A, 22A, 111A instead of 111A, 12A, 22A
SUITE 10, SUITE 20, SUITE 110, instead of SUITE 10, SUITE 110, SUITE 20
0
Comment
Question by:DanielSKim
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 29

Expert Comment

by:QPR
ID: 17886357
Not to my knowledge. Your column is a varchar and will therefore order 1-0,a-z
0
 
LVL 30

Expert Comment

by:nmcdermaid
ID: 17886396
You basically need to extract the numeric portion out of the data and order it that way.

You have two options:

1. Have a humungous CASE statement which extracts the numeric portion on the fly and orders by it.. you need to have an option for every   single format that that the data is entered.
2. Create a UDF that extracts the numeric part. This will simplify the code but slwo down your report.
3. Do some data cleansing on your table and load it into a new clean table, and select from the clean table.

I recommend option 3 but you might have some constraints on what you can do.


To give you some ideas about option 1:

SELECT *
FROM YourTable
ORDER BY

CASE WHEN ISNUMERIC(ApartmentNumber) =1 THEN CONVERT(INT,ApartmentNumber) ELSE 0 END,
ApartmentNumber


What this does is has two ordering criteria.

It first orders by the apartment number if it is totally numeric.
If the apartment number is not totally numeric it orders by the apartment number alphabetically.

This does not do what you requested but it gives you an idea of the complexity required if you want to try and do this on the fly.
0
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
ID: 17886562
Hi DanielSKim,

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


ALTER   function dbo.fnExtractNumeric (
@string varchar(1000)
) returns int
AS
BEGIN

    DECLARE @newstring varchar(1000)
    DECLARE @retVal int
    declare @num int
    select @newstring = ''
    select @num = 1
   
    while @num < len(@string)+1
    begin
   
        if Substring(@string, @num, 1) >= '0' and Substring(@string, @num, 1) <= '9'
             set @newstring = @newstring + Substring(@string, @num, 1)
        ELSE
                     set @newstring = @newstring + ASCII(Substring(@string, @num, 1))
        set @num = @num + 1
    end
    SELECT @RetVal = @newstring
    RETURN (@newstring)  --(cast @newstring  as int)
END


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO



ALTER function fn_SortCSVString(
@CSVString     varchar(8000)
)
returns varchar(1000)
as
/*
select dbo.fn_SortCSVString('1,11,2,24,3')
*/

begin
    declare @s  varchar(1000)
    declare @tbl table (s varchar(100))
    declare @i int , @j int
    select     @i = 1
    while @i <= len(@CSVString)
    begin
        select    @j = charindex(',', @CSVString, @i)
        if @j = 0
        begin
            select    @j = len(@CSVString) + 1
        end
        insert    @tbl
        select substring(@CSVString, @i, @j - @i)
        select    @i = @j + 1
    end
    DECLARE @tbl2 TABLE (S varchar(1000))
    INSERT INTO @tbl2(S)
    SELECT S
        FROM @tbl
    ORDER BY dbo.fnExtractNumeric(S)

    SELECT @S = COALESCE(@s+',','')+S
        FROM @tbl2
    RETURN( @S)


end
GO

select dbo.fn_SortCSVString('1,11,2,24,3')


Cheers!
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how the fundamental information of how to create a table.

717 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question