2

I'd like to apply the value of a column in the Nth row of my table to all rows in the table. Is this possible in PostgreSQL alone?

1
  • What do you mean "apply the value of a column"? Can you provide some example of code you have tried or what the data looks like? Commented Mar 21, 2013 at 20:22

2 Answers 2

3
select *   
from <<TABLE>>  
limit 1 offset <N>  

Edit: Sorry, misread your message. I didn't realize you needed an update as well.

UPDATE <<TABLE1>> 
SET <<COLUMN1> = (SELECT <<COLUMN2>> FROM <<TABLE2>> limit 1 offset <<N>>)

Postgres Docs

Sign up to request clarification or add additional context in comments.

1 Comment

OFFSET <<N-1>> to be precise. And it can be from the same column, too.
0

If you didn't have write access, you could do something with window functions. This could probably be simplified or expanded (particularly with how it grabs 'n', depending on the use case). Unfortunately, you cannot have window functions within window functions.

create temp table test(val numeric);
insert into test select * from generate_series(101,200,1);

select max(case when rn = n then val else null end) over () as nthvalue, val
from(
select row_number() over (order by val) as rn, val, n 
from (select val, 9 as n from test) as added_n) as obtained_rownum;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.