使用字母数字和特殊字符值对 varchar 进行排序

Sort varchar with alpha numeric and special character values

我有一个 invoice_number 字段作为 varchar(20)

我有 select 查询

SELECT Row_Number() OVER(ORDER BY case isnumeric(invoice_number) 
                                       when 1 then convert(bigint,invoice_num)
                                       else 99999999999999999999 
                                  end) As id, 
       name,
       submit_date,
       invoice_number,
       invoice_total,
       currency_code
FROM vw_invoice_report

在某些情况下效果很好,但我无法使其适用于所有 invoice_number 值,如下所示

f8ad2a28ddad4f6aa4df
0B849D69741145379079
20190313176617593442
ATOctober2000Promise
00100001010000000061
E285567EF0D0885E9160
SC1805000123000293
1999bernstyin2010
20600006307FFGMG
REVISED INVOICE F...
1111-2222(changzhou)
667339, 667340, 6...
18.12733562GAGA L...
IN-US01235055    ...
SSR-USD/426/2019 - 2
Nanny; Park Doug
184034
376840
376847-1
72692
72691
72690
72689

正在获取上述某些数据的 Error converting data type varchar to bigint.,有人可以帮我让它适用于上述测试数据吗?

嗯。我想这可能会做你想做的事:

row_number() over (order by (case when isnumeric(invoicenumber) = 1
                                  then len(invoicenumber)
                                  else 99999
                                  end
                            ),
                            invoicenumber
                  )

您的问题是您的某些发票编号(例如 20190313176617593442)对于 BIGINT 数据类型来说太大了。您可以通过将值保留为字符串来解决此问题,并用 0 将数字左填充到 20 位数字以进行排序。例如:

SELECT Row_Number() OVER(ORDER BY case isnumeric(invoice_number) 
                                       when 1 then REPLACE(STR(invoice_number, 20), ' ', '0') 
                                       else '99999999999999999999'
                                  end) As id,

SQLFiddle

上的演示(还显示转换后的发票编号)

更新

根据 OP 注释和要排序的附加值,此查询应满足该要求:

SELECT Row_Number() OVER(ORDER BY case 
                                       when isnumeric(invoice_number) = 1 then RIGHT('00000000000000000000' + REPLACE(invoice_number, '.', ''), 20) 
                                       when invoice_number like '%[0-9]-[0-9]%' and invoice_number not like '%[^0-9]' then REPLACE(STR(REPLACE(invoice_number, '-', '.'), 20), ' ', '0')
                                       else '99999999999999999999'
                                  end) As id,
       invoice_number
FROM vw_invoice_report

Demo on SQLFiddle