SQL to output line number in results of a query

后端 未结 5 482
忘了有多久
忘了有多久 2021-01-07 17:38

I would like to generate a line number for each line in the results of a sql query. How is it possible to do that?

Example: In the request

select di         


        
5条回答
  •  执笔经年
    2021-01-07 18:25

    It depends on the database you are using. One option that works for SQL Server, Oracle and MySQL:

    SELECT ROW_NUMBER() OVER (ORDER BY SomeField) AS Row, *
    FROM SomeTable
    

    Change SomeField and SomeTable is according to your specific table and relevant field to order by. It is preferred that SomeField is unique in the context of the query, naturally.

    In your case the query would be as follows (Faiz crafted such a query first):

    SELECT ROW_NUMBER() OVER (ORDER BY client_name) AS row_number, client_name
    FROM (SELECT DISTINCT client_name FROM deliveries) TempTable
    

    I think it won't work for SQLite (if someone can correct me here I would be grateful), I'm not sure what's the alternative there.

提交回复
热议问题