gpt4 book ai didi

sql - 如何按数字顺序对字母数字 SQL Server NVARCHAR 列进行排序?

转载 作者:行者123 更新时间:2023-12-01 13:37:09 24 4
gpt4 key购买 nike

我有以下 SQL:

SELECT fldTitle 
FROM tblTrafficAlerts
ORDER BY fldTitle

按以下顺序返回结果(来自 NVARCHAR 列):

A1M northbound within J17 Congestion
M1 J19 southbound exit Congestion
M1 southbound between J2 and J1 Congestion
M23 northbound between J8 and J7 Congestion
M25 anti-clockwise between J13 and J12 Congestion
M25 clockwise between J8 and J9 Broken down vehicle
M3 eastbound at the Fleet services between J5 and J4A Congestion
M4 J19 westbound exit Congestion

您会看到 M23 和 M25 列在 M3 和 M4 行的上方,这看起来不太顺眼,如果扫描更长的结果列表,您不会期望按此顺序阅读它们。

因此我希望结果按字母顺序排序,然后按数字排序,如下所示:

A1M northbound within J17 Congestion
M1 J19 southbound exit Congestion
M1 southbound between J2 and J1 Congestion
M3 eastbound at the Fleet services between J5 and J4A Congestion
M4 J19 westbound exit Congestion
M23 northbound between J8 and J7 Congestion
M25 anti-clockwise between J13 and J12 Congestion
M25 clockwise between J8 and J9 Broken down vehicle

所以 M3 和 M4 出现在 M23 和 M25 之上。

最佳答案

这应该可以处理。还添加了一些奇怪的数据以确保排序也适用于该数据:

SELECT x
FROM
(values
('A1M northbound within J17 Congestion'),
('M1 J19 southbound exit Congestion'),
('M1 southbound between J2 and J1 Congestion'),
('M23 northbound between J8 and J7 Congestion'),
('M25 anti-clockwise between J13 and J12 Congestion'),
('M25 clockwise between J8 and J9 Broken down vehicle'),
('M3 eastbound at the Fleet services between J5 and J4A Congestion'),
('M4 J19 westbound exit Congestion'),('x'), ('2'), ('x2')) x(x)
ORDER BY
LEFT(x, patindex('%_[0-9]%', x +'0')),
0 + STUFF(LEFT(x,
PATINDEX('%[0-9][^0-9]%', x + 'x1x')),1,
PATINDEX('%_[0-9]%', x + '0'),'')

结果:

2
A1M northbound within J17 Congestion
M1 J19 southbound exit Congestion
M1 southbound between J2 and J1 Congestion
M3 eastbound at the Fleet services between J5 and J4A Congestion
M4 J19 westbound exit Congestion
M23 northbound between J8 and J7 Congestion
M25 anti-clockwise between J13 and J12 Congestion
M25 clockwise between J8 and J9 Broken down vehicle
x
x2

关于sql - 如何按数字顺序对字母数字 SQL Server NVARCHAR 列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com