How to determine position of row in sql result-set?

前端 未结 5 811
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 23:08

i have a sql query:

select id, name from table order by name

result looks like this:

52 arnold 
33 berta 
34 chris 
47 dori         


        
相关标签:
5条回答
  • 2020-12-18 23:35

    Assuming SQL 2005, you can use Row_Number

    0 讨论(0)
  • 2020-12-18 23:40

    The answer depends on which version of SQL you are using.

    If you are using MSSQL 2005 you can use the the new analytical function ROW_NUMBER () which generates the sequential number in order which we define in order by clause. The syntax of ROW_NUMBER () function is:

    ROW_NUMBER () OVER (ORDER BY )

    or

    ROW_NUMBER () OVER (PARTITION BY )

    If you are using an older version of SQL Server you can create a temp table with an identity column and select the results from that.

    0 讨论(0)
  • 2020-12-18 23:45

    You don't mention which RDBMS you're running, but if you're using SQL Server 2005 or greater, you can employ the ROW_NUMBER() function - like this:

    SELECT id, name, ROW_NUMBER() OVER (ORDER BY name) AS RowNumber
    FROM   MyTable
    

    Then, to fetch a given row, you can use a derived table or a common table expression - like this:

    ;WITH NumberedRows
    AS
    (SELECT id, name, ROW_NUMBER() OVER (ORDER BY name) AS RowNumber
    FROM    MyTable)
    SELECT RowNumber FROM NumberedRows WHERE id = 47
    

    To sort out "which page" the record is on, you would need to divide the row number by the number of records per page, and round up to the nearest integer.

    0 讨论(0)
  • 2020-12-18 23:50

    The previous posts are correct. Use ROW_NUMBER if using Microsoft SQL Server 2005 or greater.

    However, your tags do not specify that you're using MSSQL, so here's a solution that should work across most RDBMS implementations. Essentially, use a correlated subquery to determine the count of rows in the same set that are less than the current row, based on the values of the ORDER clause of the outer query. Something like this:

    SELECT      T1.id,
                T1.[name],
                (SELECT COUNT(*) 
                 FROM table T2 
                 WHERE T2.[name] < T1.[name]) + 1 AS rowpos
    FROM        table T1
    ORDER BY    T1.[name]
    
    0 讨论(0)
  • 2020-12-18 23:56

    use Row_Number

    0 讨论(0)
提交回复
热议问题