Add a row number to result set of a SQL query

后端 未结 3 1570
故里飘歌
故里飘歌 2020-12-04 23:55

I have a simple select statement. I want to add a temporary column which will number the rows in my result set. I tried this -

declare @num int
set @num = 0         


        
相关标签:
3条回答
  • 2020-12-05 00:17

    The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):

    SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
      FROM dbo.tableZ AS t
      ORDER BY t.A;
    

    Not sure what the variables in your question are supposed to represent (they don't match).

    0 讨论(0)
  • 2020-12-05 00:27
    SELECT
        t.A,
        t.B,
        t.C,
        ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
    FROM tableZ AS t
    

    See working example at SQLFiddle

    Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

    0 讨论(0)
  • 2020-12-05 00:27

    So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:

    SET @row_number = 0;
    SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
    FROM dbo.tableZ AS t ORDER BY t.A;
    
    0 讨论(0)
提交回复
热议问题