简体   繁体   English

SQL Oracle排序字符串(数字)和(带数字的字母)

[英]SQL Oracle Sort string (numbers) and (letters with numbers)

I am new to oracle and I have a problem. 我是oracle的新手,我遇到了问题。 I have a column named file_id. 我有一个名为file_id的列。

When I do an order by it sorts strings such as 当我按顺序排序时,它会排序

1
1 
10 
100 
11 
11
110 
114
12
300 
31
4200
B14
B170
B18

edit: I would like it to sort this way. 编辑:我希望它以这种方式排序。

1
1
10
11
11
12
31
100
300
4200
B14
B18 
B170

The answer below works perfectly. 以下答案非常有效。 Only other problem I ran into now..I have records that are blank. 我现在遇到的其他问题......我的记录是空白的。 How could I make the blank records order at the end? 我怎么能在最后制作空白唱片?

1 
1 
10 
11 
11 
12 
31 
100 
300 
4200 
BLANK 
BLANK 
BLANK 
BLANK 
BLANK 
B14 
B18 
B170

Thank you for your help. 谢谢您的帮助。

select column 
from table
order by 
  regexp_substr(column, '^\D*') nulls first,
  to_number(regexp_substr(column, '\d+'))

fiddle 小提琴

This is an old question, but it was the first hit on google so I thought I'd share an alternative solution: 这是一个老问题,但它是谷歌的第一个热门,所以我想我会分享另一种解决方案:

select column
from table
order by 
  LPAD(column, 10)

The LPAD function pads the left-side of the string with spaces so that the results will be sorted numerically. LPAD函数用空格填充字符串的左侧,以便以数字方式对结果进行排序。 This works for non-numeric values, and null values will be sorted last. 这适用于非数字值,空值将最后排序。 This works well if you know the maximum length of the strings to be sorted (you may need to adjust the second parameter to suit your needs). 如果您知道要排序的字符串的最大长度(您可能需要调整第二个参数以满足您的需要),这很有效。

Source: http://www.techonthenet.com/oracle/questions/sort1.php 资料来源: http//www.techonthenet.com/oracle/questions/sort1.php

EDIT : 编辑
I noticed that while my solution works well for my case, the output is slightly different from the accepted answer ( http://www.sqlfiddle.com/#!4/d935b8/2/0 ): 我注意到虽然我的解决方案适合我的情况,但输出与接受的答案略有不同( http://www.sqlfiddle.com/#!4/d935b8/2/0 ):

1
1
10
11
11
12
31
100
110
114
300
A14
A18
4200
A170
(null)
(null)

4200 should come after 300. For my situation this is good enough, but this may not always be the case. 4200应该在300之后。对于我的情况,这已经足够了,但情况可能并非总是如此。

Based on the previous solution: 基于以前的解决方案:

SELECT column
FROM table
ORDER BY LPAD(column, (SELECT MAX(LENGTH(column)) FROM table)) ASC

The advantage of this approach is that you don't need know the table column size. 这种方法的优点是您不需要知道表列大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM