Solved

ORDER BY a Column with Numeric Values

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

In this article—a derivative of my DaytaBase.org blog post (http://daytabase.org/2011/06/18/what-week-is-it/)—I will explore a few different perspectives on which week today's date falls within using Microsoft SQL Server. First, to frame this stu…
When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Via a live example, show how to shrink a transaction log file down to a reasonable size.
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…

760 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now