如何在postgres中选择行号.
我试过这个:
select
row_number() over (ORDER BY cgcode_odc_mapping_id)as rownum,
cgcode_odc_mapping_id
from access_odc.access_odc_mapping_tb
order by cgcode_odc_mapping_id
Run Code Online (Sandbox Code Playgroud)
并得到此错误:
ERROR: syntax error at or near "over" LINE 1: select row_number() over (ORDER BY cgcode_odc_mapping_id)as
我检查过这些页面:如何在PostgreSQL查询中显示行号?
这是我的查询:
select row_number() over (ORDER BY cgcode_odc_mapping_id)as rownum,cgcode_odc_mapping_id from access_odc.access_odc_mapping_tb order by cgcode_odc_mapping_id
Run Code Online (Sandbox Code Playgroud)
这是错误:
错误:语法错误在"超过"LINE 1处或附近:选择row_number()over(ORDER BY cgcode_odc_mapping_id)as
我试图从一个表插入另一个表使用
DECLARE @IDOffset int;
SELECT @IDOffset = MAX(ISNULL(ID,0)) FROM TargetTable
INSERT INTO TargetTable(ID, FIELD)
SELECT [Increment] + @IDOffset ,FeildValue
FROM SourceTable
WHERE [somecondition]
Run Code Online (Sandbox Code Playgroud)
TargetTable.ID不是标识列,这就是为什么我必须找到一种自己增加它的方法.
我知道我可以使用游标,或者创建一个带有标识列和FieldValue字段的表变量,填充它,然后在我的中使用它insert into...select,但这不是很有效.我尝试使用ROW_NUMBER函数来递增,但我在SourceTable中确实没有合法的ORDER BY字段可以使用,并且希望保留SourceTable的原始顺序(如果可能).
谁能提出任何建议?
我需要使用Rails获取上一个和下一个活动记录对象.我做到了,但不知道这是否是正确的方法.
我得到了什么:
控制器:
@product = Product.friendly.find(params[:id])
order_list = Product.select(:id).all.map(&:id)
current_position = order_list.index(@product.id)
@previous_product = @collection.products.find(order_list[current_position - 1]) if order_list[current_position - 1]
@next_product = @collection.products.find(order_list[current_position + 1]) if order_list[current_position + 1]
@previous_product ||= Product.last
@next_product ||= Product.first
Run Code Online (Sandbox Code Playgroud)
product_model.rb
default_scope -> {order(:product_sub_group_id => :asc, :id => :asc)}
Run Code Online (Sandbox Code Playgroud)
所以,这里的问题是我需要进入我的数据库并获取所有这些ID以了解谁是前一个和下一个.
尝试使用gem order_query,但它对我不起作用,我注意到它进入数据库并按顺序获取所有记录,所以,这就是为什么我做了同样但只得到id.
我发现的所有解决方案都是简单的订单查询.按ID排序或类似优先级字段.
可能重复:
如何在PostgreSQL查询中显示行号?
在Postgresql PostgreSQL中重新排序带有标识符的列使用带子
选择的更新重新排序
我只是问在PostgreSQL中是否存在这样的可能性:如果我有5行并且在一列中有数字1, 2, 3, 4, 5并且在那些列中不是主键如果我删除说tird行postgreSQL重新枚举这个列所以我可以1, 2, 3, 4代替1, 2, 4, 5?
为了测试目的,我需要编写一个SQL查询,其中包含实际记录号作为结果集中的列.如果我的SELECT返回给我10个记录作为结果,我需要有一个包含值1-10的列.
有没有办法在没有存储过程的情况下通过我的数据来实现这一点?
我在PostgreSQL上需要这个.