Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a query that outputs the row number as a column?

Tags:

sql

db2

How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries.

eg if I have

table Beatles:

John
Paul
George
Ringo

and I want to write a statement, without writing a procedure or view if possible, that gives me

1 John
2 Paul
3 George
4 Ringo
like image 718
nearly_lunchtime Avatar asked Jan 13 '09 10:01

nearly_lunchtime


People also ask

How do I create a column with row numbers 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. SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.

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.

What is ROW_NUMBER () over in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.


2 Answers

SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles
like image 177
Michael Buen Avatar answered Sep 22 '22 03:09

Michael Buen


Check out the row_number() function; you should be able to do this in DB2 via:

SELECT row_number(), first_name FROM beatles

I'm almost certain this is not part of the SQL standard though, so it is not likely to be portable should that ever be an issue.

like image 28
Andrzej Doyle Avatar answered Sep 21 '22 03:09

Andrzej Doyle