How to update the fields of a table based on other records of the same table - Postgre

Asked

Viewed 19 times

0

I have a table called SERTAB and I need to update all the "value" fields of all Branch 2 records based on branch 1 records, that is, the two branches have the same amount of records or not, but if they do, it will be necessary to do this update.

Someone knows how to do it?

inserir a descrição da imagem aqui

  • It is unclear whether you simply want to match the constant value of branch 1 in the branch 2 value field without any condition or there is some condition to be met. What identifies the value of affiliate 1 to be considered to modify affiliate 2 or all affiliate 2 records will be with the same content as affiliate 1 (in this case the first value found? The last? Other?). Is it only the value field that should be changed? Will all others remain unchanged? Explain better.

  • Only the "value" field should be updated. There is no specific condition. Only play affiliate values 1 for affiliate 2.

  • He’ll have to do it with all the records.

  • Then just take the value of the first affiliate record 1 and record this value in all affiliate records 2?

  • Yes. Now that I touched on what you had commented above if you would have any condition... He needs to compare record, by record... If in Branch 1 you have the type registration 500002 and in Branch 2 tb you have the registration 500002, you must move the value from Branch 1 to Branch 2. I think you would need some Where clause right?

1 answer

1


I think that’s what you want:

UPDATE SERTAB a
   SET a.valor = coalesce((SELECT b.valor FROM SERTAB b WHERE b.tipo = 1 AND b.tipo = a.tipo), 0)
   WHERE a.filial = 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.