0

我需要对我的 Access2010 查询中的列进行正确排序。它是一个文本列,其中包含带有“CRMPPC1”之类的数字的字符串。列中的文本长度可能会有所不同。

当我对此进行排序时,它看起来像

CRMPPC1
**CRMPPC10**
CRMPPC2
CRMPPC3
CRMPPC4
....

但我需要的是

CRMPPC1
CRMPPC2
CRMPPC3
CRMPPC4
....
**CRMPPC10**

任何人都可以帮助我(最好使用 SQL)吗?我尝试了各种方法,如 VAL、CAST 等,但到目前为止没有任何效果。

4

2 回答 2

1

如果文本前缀中的字符数是可变的那么我认为没有纯粹的Access SQL解决方案,而是VBA函数

Public Function ExtractNumber(textString As Variant) As Long
Dim s As String, i As Long
s = Nz(textString, "")
For i = 1 To Len(s)
    Select Case Mid(s, i, 1)
        Case "0" To "9"
            Exit For
    End Select
Next
If i > Len(s) Then
    ExtractNumber = 0
Else
    ExtractNumber = Val(Mid(s, i))
End If
End Function

将允许您使用这样的查询

SELECT textTest.*
FROM textTest
ORDER BY ExtractNumber([textColumn]);
于 2013-04-17T09:16:21.523 回答
0

尝试使用此“hack”进行自然顺序排序。它仅适用于两个字符,但您当然可以对其进行更多修改。

'''' 仅适用于末尾的最后两个字符数字。如果你有三个数字,它将打破'''''''

函数 PadNumberForNatSort(strToMod) 作为字符串

If IsNumeric(Right(strToMod, 1)) = True Then
    If IsNumeric(Mid(strToMod, Len(strToMod), 1)) = True And IsNumeric(Mid(strToMod, Len(strToMod) - 1, 1)) = True Then
        PadNumberForNatSort = strToMod
    Else
        PadNumberForNatSort = Mid(strToMod, 1, Len(strToMod) - 1) & "0" & Mid(strToMod, Len(strToMod), 1)
    End If
Else
    PadNumberForNatSort = strToMod
End If

结束功能

在您的 SQL 中: ORDER BY PadNumberForNatSort([column_name])

于 2014-04-21T21:13:32.270 回答