Returning row number on MS Access

穿精又带淫゛_ 提交于 2019-12-01 14:58:21

The answer by Brettski is ASP flavored and would need a lot of editing.

SELECT DCOUNT("YourField","YourTable","YourField <= '" & [counter] & "'") 
  AS RowNumber,  
  YourField as counter FROM YourTable;  

Above is your basic syntax. You are likely to find this runs very slow. My typical solution is a bucket table with Autonumber field. That seems kludgy, but it gives me control and probably in this case it allows speed.

Using a sorted Make Table Query in Access, I use the following (wouldn't work if you look at the Query, as that would increment the number when you don't want it to)....

setRowNumber 'resetting increment before running SQL
DoCmd.RunSQL ... , rowNumber([Any Field]) AS ROW, ...

'Increment Number: Used to create temporary sorted Table for export
Private ROWNUM As Long

'dummyField: must take an input to update in Query
Public Function rowNumber(ByVal dummyField As Variant, Optional ByVal incBy As Integer = 1) As Long
    ROWNUM = ROWNUM + incBy 'increments before value is returned
    rowNumber = ROWNUM
End Function

Public Function setRowNumber(Optional ByVal setTo As Long = 0) As Long
    ROWNUM = setTo
    setRowNumber = ROWNUM
End Function

With the following table

SET NOCOUNT ON 

CREATE TABLE people 
( 
    firstName VARCHAR(32), 
    lastName VARCHAR(32) 
) 
GO 

INSERT people VALUES('Aaron', 'Bertrand') 
INSERT people VALUES('Andy', 'Roddick') 
INSERT people VALUES('Steve', 'Yzerman') 
INSERT people VALUES('Steve', 'Vai') 
INSERT people VALUES('Joe', 'Schmoe')

You can use a sub query to create the counting row:

SELECT 
    rank = COUNT(*), 
    a.firstName, 
    a.lastName 
FROM 
    people a  
    INNER JOIN people b 
    ON  
        a.lastname > b.lastname 
        OR 
        ( 
            a.lastName = b.lastName 
            AND 
            a.firstName >= b.firstName 
        ) 
GROUP BY 
    a.firstName, 
    a.lastName 
ORDER BY 
    rank

The problem with this method is that the count will be off if there are duplicates in your results set.

This article explains pretty well how to add a row counting column to your query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!