简体   繁体   中英

SQl Server : sort alphanumeric first followed by Numeric

SELECT  dbo.base_project.id as ID, 
        dbo.base_project.name as Name,
        dbo.base_project.status
FROM         dbo.base_project
ORDER BY   
Case When IsNumeric(dbo.base_project.name) = 1 
     then Right(Replicate('0',21) + dbo.base_project.name, 20)
     When IsNumeric(dbo.base_project.name) = 0 
     then Left(dbo.base_project.name + Replicate('',21), 20)
     Else dbo.base_project.name End

I'm able to sort numerically then alphanumeric.I need to reverse sort, where i need to sort Alphanumeric first and then Numerical

Example:

1, 3, 13036, 101-2011-009X2, 20-100281-01, ELO-001, ELO001B, ELO002B

You can accomplish this by using a subquery. The subquery separates the numeric from the not numeric and gives them calculated fields so they can be used in the order by of the main query.

SELECT 
    A.ID
,   A.Name
,   A.status
FROM 
(
    SELECT  
        dbo.base_project.id as ID
    ,   dbo.base_project.name as Name
    ,   dbo.base_project.status
    ,   1 as ordering
    ,   RIGHT(REPLICATE('0',21) + dbo.base_project.name, 20) As padded
    FROM dbo.base_project
    WHERE ISNUMERIC(dbo.base_project.name) = 1
UNION
    SELECT  
        dbo.base_project.id as ID
    ,   dbo.base_project.name as Name
    ,   dbo.base_project.status
    ,   0 as ordering
    ,   LEFT(dbo.base_project.name + REPLICATE('',21), 20) As padded
    FROM dbo.base_project
    WHERE ISNUMERIC(dbo.base_project.name) <> 1
) A
ORDER BY A.ordering, A.padded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM