c# - 如何使用 C# 对 SQL Server 中的字母数字列进行排序?

标签 c# sql-server

我有一些数据像这样存储在 SQL Server 中:

A1
A2
A3
1A
2A
3A

如何排序?

我试过这个查询:

select name
from Analyze_Table
group by name
order by CONVERT(INT, LEFT(name, PATINDEX('%[^0-9]%', name+'z')-1)),name

但这只按第一个数字和字母顺序排序,不按字母顺序和数字值排序

最佳答案

我尝试只对名称的数字部分进行排序,不包括第一个或最后一个字符。然后如果有 2 个相同的数字,他们将再次排序,例如23 和 23A。这应该会给你你正在寻找的输出

select name
from Analyze_Table
group by name
order by case 
  when isnumeric(name) = 1 then cast(name as int)
  when isnumeric(left(name, 1)) = 0 and isnumeric(right(name, 1)) = 0 then cast(substring(name, 2, len(name)-2) as int)
  when isnumeric(left(name, 1)) = 0 then cast(right(name, len(name)-1) as int)
  when isnumeric(right(name, 1)) = 0 then cast(left(name, len(name)-1) as int) end
  ,name

关于c# - 如何使用 C# 对 SQL Server 中的字母数字列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55775443/

相关文章:

c# - 如何将类型 int[] 转换为 int?[]

c# - 想要避免在传递给 Composite 的 Strategy 中向下转型

c# - 这个开关盒怎么有无法访问的代码?

sql-server - 服务器 xxxx 的 SQL Server 备份失败

c# - 我如何使用 C# 运行 sql server 脚本?

sql-server - 什么是表提示锁的范围?

c# - 简单注入(inject)器——确保 Controller 在生产环境中有一个无参数的公共(public)构造函数

c# - rx里面有没有ThrottleOrMax之类的东西?

sql - SQL Server 中的 pivot varchar 列?

SSIS 中的 C# 脚本任务