Add a row number to result set of a SQL query

后端 未结 3 1575
故里飘歌
故里飘歌 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: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.

提交回复
热议问题