Solved

ORDER BY a Column with Numeric Values

Posted on 2006-11-06
6
266 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
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
RESTORE A BACKUP IN SQL 2012 from SQL 2008 9 64
Database Integrity 1 48
Location of Dynamics AX Service accounts in SQL 3 15
Are triggers slow? 7 10
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

809 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