Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to output line number in results of a query

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 distinct client_name from deliveries 

I would like to add a column showing the line number

I am working on sql server 2005.

like image 280
madewulf Avatar asked Aug 18 '09 11:08

madewulf


People also ask

How do I generate a row number in SQL?

To add a row number column in front of each row, add a column with the ROW_NUMBER function, in this case named Row# . You must move the ORDER BY clause up to the OVER clause.

How do I display a row value in a column in SQL?

SET @sql = CONCAT('SELECT Meeting_id, ', @sql, ' FROM Meeting WHERE <condition> GROUP BY Meeting_id'); Similarly, you can also apply JOINS in your SQL query while you display row values as columns in MySQL. After you convert row to column in MySQL, you can use a charting tool to plot the result in a table.


2 Answers

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.

like image 199
Roee Adler Avatar answered Oct 09 '22 05:10

Roee Adler


You can use the ROW_NUMBER function for this. Check the syntax for this here http://msdn.microsoft.com/en-us/library/ms186734.aspx

SELECT FirstName, LastName, ROW_NUMBER() OVER(ORDER BY FirstName) AS 'Row#'     FROM Sales.vSalesPerson; 

For your query,

SELECT client_name, ROW_NUMBER() Over (Order By client_name) AS row_number  FROM   (select distinct client_name from deliveries) SQ 

will work.

like image 27
Faiz Avatar answered Oct 09 '22 04:10

Faiz