简体   繁体   English

如何在PostgreSQL中基于排序顺序添加序数ID字段

[英]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.

相关问题 PostgreSQL:根据排序顺序仅选择每个id的第一条记录 - PostgreSQL: Select only the first record per id based on sort order PostgreSQL-ORDER BY random()但也按ID排序? - Postgresql - ORDER BY random() but also sort by id? 根据引用它的最新订单对产品进行排序 - PostgreSQL - Sort Products based on the latest Order that referenced it - PostgreSQL SQL如何根据“顺序”字段对子行进行排序? - SQL How to sort child rows based on an “order” field? 基于排序顺序旋转列但在 PostgreSQL 中具有相同名称 - Pivoting a column based on sort order but with same name in PostgreSQL 基于先前ID字段的Oracle自定义订单 - Oracle custom order based on previous id field 如何在PostgreSQL中按最大ID排序到最小ID - How to sort by biggest ID to smallest in PostgreSQL 根据另一个字段的字母顺序设置排序顺序字段 - Set sort-order field based on alphabetically ordering of another field MySQL:如何根据另一个字段的值对ASC中的某些记录和DESC顺序中的某些记录进行排序 - MySQL: how to sort some records in ASC and some in DESC order, based on another field's value 在 postgresql 中订购表格,基于具有格式编号/年份的特定字符串字段 - order a table in postgresql based in a specific string field with format number/year
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM