Can I get the position of a record in a SQL result table?

后端 未结 6 979
日久生厌
日久生厌 2020-12-16 02:35

If I do something like

SELECT * FROM mytable ORDER BY mycolumn ASC;

I get a result table in a specific order.

Is there a way in SQL

6条回答
  •  忘掉有多难
    2020-12-16 02:57

    On databases that support it, you could use ROW_NUMBER() for this purpose:

    SELECT RowNr
    FROM (
        SELECT 
             ROW_NUMBER() OVER (ORDER BY mycolumn) AS RowNr,
             mycolumn
        FROM mytable
    ) sub
    WHERE sub.mycolumn = 42
    

    The example assumes you're looking for primary key 42 :)

    The subquery is necessary because something like:

    SELECT 
         ROW_NUMBER() OVER (ORDER BY mycolumn) AS RowNr
    FROM mytable
    WHERE sub.mycolumn = 42
    

    Will always return 1; ROW_NUMBER() works after the WHERE, so to speak.

提交回复
热议问题