【问题标题】:Adding a Row Number in Query在查询中添加行号
【发布时间】:2015-07-03 14:13:33
【问题描述】:

我在 Access 2013 的数据库中有一个表。

Table : city

ID_city city
1       Tetuan
5       Rabat
9       Marrakech
10      Agadir
15      Laayoun

我希望在它们旁边添加 Rowid 编号:

Rowid   ID_city city
1       1       Tetuan
2       5       Rabat
3       9       Marrakech
4       10      Agadir
5       15      Laayoun

【问题讨论】:

标签: sql ms-access vba


【解决方案1】:

一种方法是在子查询中使用count 函数。虽然不确定它是否可以很好地扩展,但可能有更好的方法......

select 
    (select count(*) from city where ID_city <= t1.ID_city) as row_number,
    *
from city t1

【讨论】:

  • 如果结果按城市排序可能会有问题
【解决方案2】:

最好的方法是使用自连接...

    SELECT
    COUNT(*) AS Rowid,
    C.ID_City,
    C.city
    FROM City C
    INNER JOIN City C1 ON C.ID_City >= C1.ID_City
    GROUP By C.ID_City, C.city

【讨论】:

    【解决方案3】:

    一点点 VBA 大有帮助...

    'Module level variables; values will persist between function calls
    'To reset the row number, you have to explicitly call Reset
    Dim lastValue As Integer
    
    Public Function RowNumber(x) As Integer
        'We need this parameter so Access will call the function on each row, instead of only once
        lastValue = lastValue +1
        RowNumber = lastValue
    End Function
    
    Public Sub Reset()
        lastValue = 0
    End Sub
    

    SQL语句:

    SELECT RowNumber(city) AS RowID, *
    FROM City
    

    【讨论】:

      【解决方案4】:

      另一种选择:(http://www.openwinforms.com/row_number_to_sql_select.html)

        SELECT ROW_NUMBER() 
        OVER (ORDER BY ID_city) AS Rowid, 
        ID_City, city
        FROM city
      

      【讨论】:

      • ROW_NUMBER()OVER 在 Access SQL 中不受支持。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2017-04-06
      相关资源
      最近更新 更多