[英]How to add an ordinal id field based on a sort order in PostgreSQL
I was wondering how to add a field to a table (eg country
) based on sorting some of its fields (eg ISO
code)? 我想知道如何基于对某些字段(例如
ISO
代码)的排序将字段添加到表(例如country
)中?
I searched around SO and found the following question , but the solution is based on MySQL. 我搜索了SO,发现以下问题 ,但是解决方案基于MySQL。 I tried to use the solution there in Postgres 9.3 and it's giving me an syntax error on
:=
. 我尝试在Postgres 9.3中使用该解决方案,这给了我
:=
的语法错误。 What I tried is: 我试过的是:
SELECT l.*,
@curRow := @curRow + 1 AS row_number
FROM country l ORDER BY ISO
JOIN (SELECT @curRow := 0) r;
How to adapt this to Postgres? 如何适应Postgres?
You can use the row_number()
window function : 您可以使用
row_number()
窗口函数 :
SELECT country.*, ROW_NUMBER() OVER (ORDER BY iso)
FROM country
ORDER BY iso
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.