SQl Server:首先对字母数字进行排序,然后是数字

时间:2015-02-25 06:41:53

标签: sql sorting alphanumeric

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

我能用数字排序然后用字母数字排序。我需要反向排序,我需要首先排序字母数字然后数字

示例:

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

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来完成此操作。子查询将数字与非数字分开,并为它们提供计算字段,以便按主查询的顺序使用它们。

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