[英]Sorting an alphanumeric column in SQL with mix of alphanumeric and alpha-only values
I have a requirement where I have to apply sort in an SQL query by an Alphanumeric column such that the values in it get sorted like the following:我有一个要求,我必须按字母数字列在 SQL 查询中应用排序,以便其中的值按如下方式排序:
AD
AH
AK1
B1
B2
B3x
B3y
B11
C1
C6
C12x
UIP
instead of the default way:而不是默认方式:
AD
AH
AK1
B1
B11
B2
B3x
B3y
C1
C12x
C6
UIP
I was able to write the following SQL statement:我能够编写以下 SQL 语句:
SELECT [MyColumn]
FROM [MyTable]
ORDER BY
LEFT([MyColumn], PATINDEX('%[0-9]%', [MyColumn]) - 1),
CONVERT(INT, SUBSTRING([MyColumn], PATINDEX('%[0-9]%', [MyColumn]), LEN([MyColumn]) - (PATINDEX('%[0-9]%', REVERSE([MyColumn]))))),
RIGHT([MyColumn], PATINDEX('%[0-9]%', [MyColumn]) - 1)
I just need to know how to implement this in a conditional way such that this doesn't get triggered for alpha-only value else it would give error, or if there is a way to make it work with that as well?我只需要知道如何以有条件的方式实现这一点,这样就不会为 alpha-only 值触发它,否则它会出错,或者是否有办法让它与它一起工作?
PS The environment is SQL Server 2014. PS环境是SQL Server 2014。
It is a bit of a mess to look at and I agree with Sean Lange that you should look into recording this in more than one field, but you can use case
expressions within your order by
to have conditional ordering:看起来有点混乱,我同意 Sean Lange 的观点,即您应该考虑在多个字段中记录这一点,但是您可以在
order by
使用case
表达式来进行条件排序:
declare @t table(c nvarchar(10));
insert into @t values('AD'),('AH'),('AK1'),('B1'),('B2'),('B3x'),('B3y'),('B11'),('C1'),('C6'),('C12x'),('UIP');
select c
from @t
order by
case when patindex('%[0-9]%', c) = 0
then c
else left(c, patindex('%[0-9]%', c) - 1)
end
,case when patindex('%[0-9]%', c) = 0
then 0
else convert(int,substring(c,patindex('%[0-9]%', c),len(c) - (patindex('%[0-9]%', reverse(c)))))
end
,right(c,case when patindex('%[0-9]%', c) = 0
then 0
else patindex('%[0-9]%', c) - 1
end
);
Output:输出:
+------+
| c |
+------+
| AD |
| AH |
| AK1 |
| B1 |
| B2 |
| B3x |
| B3y |
| B11 |
| C1 |
| C6 |
| C12x |
| UIP |
+------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.