简体   繁体   English

排序列包含数字和字母数字值时,SQL排序失败

[英]SQL sort failing when sorted column contains both numeric and alphanumeric values

I'm attempting to sort by a field with may contain either numbers, or a letter followed by a number. 我试图按字段排序,可能包含数字,或后跟数字的字母。 (But not a mix of both). (但不是两者的混合)。

My Sort ascending field is 我的排序升序字段是

 sField: IIf(Val([AlbumTrack]) > 0, CInt([AlbumTrack]), [AlbumTrack])

But numbers are not sorting correctly. 但数字没有正确排序。 Letter and numbers seem to be. 字母和数字似乎是。 What am I doing wrong ? 我究竟做错了什么 ?

Examples of data are 7,8,9,10,11 A3, A4, A5, B1, B2, C1 数据的例子是7,8,9,10,11 A3,A4,A5,B1,B2,C1

My sql is 我的sql是

SELECT DISTINCTROW 
    CDTracks.AlbumCat, CDTracks.AlbumTrack, 
    IIf(Val([AlbumTrack])>0,CInt([AlbumTrack]),[AlbumTrack]) AS sField
FROM 
    CDTracks
WHERE 
    (((CDTracks.AlbumCat) = "RCA Victor LSP 2525"))
ORDER BY 
    IIf(Val([AlbumTrack]) > 0, CInt([AlbumTrack]), [AlbumTrack]);

Hmm, I see what you mean. 嗯,我明白你的意思了。 The issue appears to be that the expression in your ORDER BY clause does not have a consistent data type: for some rows it evaluates to an Integer and for other rows it evaluates to a String. 问题似乎是ORDER BY子句中的表达式没有一致的数据类型:对于某些行,它将计算为Integer,而对于其他行,它将计算为String。

The following worked for me because the expression in this ORDER BY clause always returns a String: 以下内容对我有用,因为此ORDER BY子句中的表达式始终返回一个String:

SELECT DISTINCTROW
    CDTracks.AlbumCat, CDTracks.AlbumTrack
FROM 
    CDTracks
WHERE 
    (((CDTracks.AlbumCat) = "RCA Victor LSP 2525"))
ORDER BY 
    IIf(Val([AlbumTrack]) > 0, Right("00000" & [AlbumTrack], 5), [AlbumTrack]);

If I understand your question correctly, this query shold return rows in the order that you want: 如果我正确理解您的问题,此查询将按您想要的顺序返回行:

SELECT DISTINCTROW 
    CDTracks.AlbumCat, CDTracks.AlbumTrack
FROM 
    CDTracks
WHERE 
    CDTracks.AlbumCat = "RCA Victor LSP 2525"
ORDER BY
  IIf(Val([AlbumTrack]) > 0, Null, Left([AlbumTrack], 1)),
  IIf(Val([AlbumTrack]) > 0, CInt([AlbumTrack]), CInt(MID([AlbumTrack], 2)));

This will split the AlbumTrack column in two different columns: one for the alphanumeric part if present, one for the numeric part. 这会将AlbumTrack列拆分为两个不同的列:一个用于字母数字部分(如果存在),一个用于数字部分。

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

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