SQL 如何对带数字的文本按字母顺序排序,然后按数字排序

SQL how to sort text with numbers alphabetically, then numerically

我有一个具有字母数字值的 table。我想按字母顺序然后按数字顺序排列它们。我正在编辑问题以获得更多帮助...我只需要对字符串末尾的数字进行数字排序...

我想要这个例子

ControlName (column)
--------------------
VALVE 1
MAIN VALVE
VALVE 10
BOILER 2
VALVE 17
BOILER 1
VALVE 19
VALVE 2

按此排序

ControlName (column)
----------------
BOILER 1
BOILER 2
MAIN VALVE
VALVE 1
VALVE 2
VALVE 10
VALVE 17
VALVE 19

什么是可以完成此任务的(简单)查询?

这是一个函数,可以在文本末尾的数字前添加最多两个零。例如锅炉 1 将成为锅炉 001,锅炉 12 将成为锅炉 012。

CREATE FUNCTION [dbo].[sortTextWithNum](@text nvarchar(max))
returns nvarchar(max) as 
begin
    declare @reverse nvarchar(max) = reverse(@text)
    declare @numIndex int = patindex('%[^0-9]%', @reverse)
    return iif(@numIndex=1, @text, substring(@text, 0, len(@text)-@numIndex+2) + format(cast(reverse(left(@reverse, @numIndex-1)) as int),'D3'))
end

你可以这样使用它:

select ControlName from [YourTable] order by dbo.sortTextWithNum(ControlName)

由于现在的问题在于,如果字符串中有不止一组数字部分,我们希望按最后一组数字排序。此代码将执行此操作。如果只有一组数字,甚至没有数字,这都有效。

declare @Something table
(
    ControlName varchar(50)
)

insert @Something values
('VALVE 1')
, ('MAIN VALVE')
, ('VALVE 10')
, ('BOILER 2')
, ('VALVE 17')
, ('BOILER 1')
, ('VALVE 19')
, ('VALVE 2')

select *
from @Something
order by left(ControlName, LEN(ControlName) - patindex('%[^0-9]%', REVERSE(ControlName)) + 1) --this gets the "prefix" or characters before the last set of numbers
    , convert(int, right(ControlName, patindex('%[^0-9]%', REVERSE(ControlName)) - 1)) --this gets the last set of numbers

我认为更简单的顺序说明是:

select *
from @something s
order by left(ControlName, patindex('%[0-9]%', ControlName + '0') - 1),
         len(ControlName),
         ControlName

按键顺序执行以下操作:

  • 按第一个数字之前的所有内容排序。
  • 按控件名称的长度排序,因此较短的数字 (1) 在较大的数字 (100) 之前。
  • 按名字排序,所以数字是有序的。