SQLServer SQL query with a row counter

后端 未结 4 1523
花落未央
花落未央 2021-02-01 05:09

I have a SQL query, that returns a set of rows:

SELECT id, name FROM users where group = 2

I need to also include a column that has an incremen

4条回答
  •  臣服心动
    2021-02-01 05:54

    The simplest way is to use a variable row counter. However it would be two actual SQL commands. One to set the variable, and then the query as follows:

    SET @n=0;
    SELECT @n:=@n+1, a.* FROM tablename a
    

    Your query can be as complex as you like with joins etc. I usually make this a stored procedure. You can have all kinds of fun with the variable, even use it to calculate against field values. The key is the :=

提交回复
热议问题