SQL:排序有序查询

时间:2012-09-22 02:07:06

标签: sql ms-access

我在Access 2010中,正在尝试为以特定方式排序的查询创建排名或行号字段。我尝试了Rank: DCount("id","[Query1]","id <= " & [id]),但它忽略了我的查询排序,因为订单不是ID主键。

2 个答案:

答案 0 :(得分:1)

我已经看到了你的排序逻辑,似乎我设法通过创建一个额外的查询(Temp)来生成基于它的排名,其中一列包含连接在其中的所有排序函数子产品。此查询的代码应如下所示:

SELECT Table1.Code1, 
    Len(Mid([Code1] & "",1,IIf(InStr([Code1] & "","*")>0,InStr([Code1] & "","*")-1,Len([Table1].[Code1] & "")))) 
    & Mid([Code1] & "",1,IIf(InStr([Code1] & "","*")>0,InStr([Code1] & "","*")-1,Len([Table1].[Code1] & ""))) & 
    Val(Mid([Code1] & "",InStr([Code1] & "","*")+1)) & 
    CStr(Val(Mid([Code1] & "",InStr([Code1] & "","*")+1))) AS OrderCode1
FROM Table1
ORDER BY Len(Mid([Code1] & "",1,IIf(InStr([Code1] & "","*")>0,InStr([Code1] & "","*")-1,Len([Table1].[Code1] & "")))), 
    Mid([Code1] & "",1,IIf(InStr([Code1] & "","*")>0,InStr([Code1] & "","*")-1,Len([Table1].[Code1] & ""))), 
    Val(Mid([Code1] & "",InStr([Code1] & "","*")+1)), 
    CStr(Val(Mid([Code1] & "",InStr([Code1] & "","*")+1))), Table1.Code1;

之后,如果您通过DCount参数创建一个查询,并在WHERE参数上使用带有'OrderCode1'列的SELECT Temp.Code1, DCount("Code1","[Temp]","OrderCode1 <= '" & [OrderCode1] & "'") AS Rank FROM Temp; 函数,则应获得顺序排名。像这样:

{{1}}

如果您仍然需要解决方案,可以检查它是否有效!

答案 1 :(得分:-1)

希望这有帮助

SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNo, OrderID FROM Orders