sql – 以varchar字母顺序排序数据

我有以下数据表.

 1
 AAAAA01 
 AAAAA01
 AAAAA01
 B21
 AAAAAA1
 B3
 AB100

我想按以下顺序对数据进行排序

 AAAAAA1
 AAAAA01
 AAAAA01
 AAAAA01
 AB100
 B21
 B3
 1

我写了一个声明,但没有给我正确的结果.

    Select
    *
from
    dbo.Section
order by      
    CASE    
      WHEN not Section like '%[^0-9]%' THEN CONVERT(int,Section)
      WHEN  Section like '[0-9]%' THEN CONVERT(int,SUBSTRING(Section,1,PATINDEX('%[A-Z]%',Section)-900000))
    END

为了你的帮助,我提供表格的脚本

  INSERT [dbo].[Section] ([Section]) VALUES (N'1')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAA01')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAA01')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAA01')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAA01')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAA01')
INSERT [dbo].[Section] ([Section]) VALUES (N'B21')
INSERT [dbo].[Section] ([Section]) VALUES (N'AAAAAA1')
INSERT [dbo].[Section] ([Section]) VALUES (N'B3')
INSERT [dbo].[Section] ([Section]) VALUES (N'AB100')
INSERT [dbo].[Section] ([Section]) VALUES (N'2')
INSERT [dbo].[Section] ([Section]) VALUES (N'B1')
INSERT [dbo].[Section] ([Section]) VALUES (N'B32')
INSERT [dbo].[Section] ([Section]) VALUES (N'11')
INSERT [dbo].[Section] ([Section]) VALUES (N'A10')
INSERT [dbo].[Section] ([Section]) VALUES (N'ABAAAA') 

你能告诉我这怎么能给我正确的答案.

最佳答案 请试试:

Select    
    *
from
    dbo.Section
order by
    REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE
    (REPLACE ([Section], '0', 'ZZ0'),
    '1', 'ZZ1'),
    '2', 'ZZ2'),
    '3', 'ZZ3'),
    '4', 'ZZ4'),
    '5', 'ZZ5'),
    '6', 'ZZ6'),
    '7', 'ZZ7'),
    '8', 'ZZ8'),
    '9', 'ZZ9'),
    [Section]

Sqlfiddle

选择新测试数据的结果:
《sql – 以varchar字母顺序排序数据》

请检查一下是否正确.

点赞