SQL 如何编写将行号输出为列的查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/438610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:43:19  来源:igfitidea点击:

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

sqldb2

提问by nearly_lunchtime

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

如何编写将行号输出为列的查询?这是 iSeries 上的 DB2 SQL。

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

回答by Michael Buen

SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles

回答by Andrzej Doyle

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

查看 row_number() 函数;您应该能够通过以下方式在 DB2 中执行此操作:

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.

我几乎可以肯定这不是 SQL 标准的一部分,所以如果这成为一个问题,它不太可能是可移植的。

回答by RAJNISH KUMAR

SELECT ROW_NUMBER() OVER(ORDER BY BEATLE_NAME) ROWNUM,BEATLE_NAME FROM BEATLES;