database 如何在查询中生成序列号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4731973/
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
How to generate serial number in a query?
提问by Gnanam
We're using PostgreSQL v8.2.3.
我们使用的是 PostgreSQL v8.2.3。
How do I generate serial number in the query output? I want to display serial number for each row returned by the query.
如何在查询输出中生成序列号?我想显示查询返回的每一行的序列号。
Example: SELECT employeeid, name FROM employee
例子: SELECT employeeid, name FROM employee
I expect to generate and display serial number against each row starting from one.
我希望从一行开始生成并显示每一行的序列号。
回答by Yodan Tauber
You have two options.
你有两个选择。
Either upgrade to PostgreSQL v8.4 and use the row_number()
function:
升级到 PostgreSQL v8.4 并使用该row_number()
功能:
SELECT row_number() over (ORDER BY something) as num_by_something, *
FROM table
ORDER BY something;
Or jump through some hoops as described in Simulating Row Number in PostgreSQL Pre 8.4.
或者如在 PostgreSQL Pre 8.4中模拟行号中所述跳过一些障碍。
回答by a_horse_with_no_name
SELECT row_number() over (order by employeeid) as serial_number, employeeid, name FROM employee
If you want to assign the numbers according to the sorting of the name, change the order by in the over
clause
如果要根据名称的排序来分配数字,请更改over
子句中的顺序