【问题标题】:How to sort rows in SQL that contain both numeric and alphanumeric values in ascending order?如何按升序对包含数字和字母数字值的 SQL 行进行排序?
【发布时间】:2020-05-11 21:36:29
【问题描述】:

我的 SQL 查询返回了以下行 - 有人可以帮助使用通用排序代码按升序对值进行排序吗?

('High_Speed'),
('M1 Speed'),
('M13 Speed'),
('M14 Speed'),
('M2 Speed'),
('M3 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone21 High_Speed'),
('Medium_Speed'),
('Zone206 Speed')

预期排序-

('High_Speed'),
('M1 Speed'),
('M2 Speed'),
('M3 Speed'),
('M13 Speed'),
('M14 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone21 High_Speed'),
('Medium_Speed'),
('Zone206 Speed')

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 不是一个好方法。即使在通用编程语言中,这个问题也很难分类(字符串是不透明的值,没有一般的内容知识)。理想情况下,可能会使用其他信息。
  • 另一种方法可能是将所有 nnnn、nnn、nn、n 转换为用于排序的值的 nnnn、0nnn、00nn、000n(转换仍然是字符串)。

标签: sql sorting alphanumeric


【解决方案1】:

最通用的方法是使用case 表达式:

order by (case col
            when 'High_Speed' then 1
            when 'M1 Speed' then 2
            when 'M2 Speed' then 3
            when 'M3 Speed' then 4
            when 'M13 Speed' then 5
            when 'M14 Speed' then 6
            when 'Medium_Speed' then 7
            when 'Test1 zone1 High_Speed' then 8
            when 'Test1 zone2 High_Speed' then 9
            when 'Test1 zone11 High_Speed' then 10
            when 'Test1 zone21 High_Speed' then 11
            when 'Medium_Speed' then 12
            when 'Zone206 Speed' then 13
            else 999
          end)

【讨论】:

  • 如果这是一个提出的解决方案,即使编写查询也没有任何意义,因为它只适用于特定数据。(或者,也可以编写一个带有显式排序列的表)。
  • @user2864740 。 . .这回答了OP提出的问题。如果您有其他问题,请将其作为新问题提出。
  • 这似乎是硬编码-原因是我的行将被动态返回,并且不会总是包含与我在上面的问题中发布的相同的字符串。有没有更好的方法/解决方案代码来解决这个问题?
  • @Rajeev 。 . .然后你应该问一个新的问题,并且更清楚你用于订购的规则。这回答了您在此处提出的问题。
  • 如果问题写得不好或缺乏细节(嗯,没有密切投票关注焦点或 cmets 要求相关细节?),考虑不要简单地写一个“答案”来填充投票..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
相关资源
最近更新 更多