Skip to content
Advertisement

SQL: Update every entry with value from another entry that share same column value

I have the following table trn_ReceiptLog

enter image description here

I am wondering if it’s possible to update amount of entry #1 to have same as entry #2 IF amount of entry #1 is 0?

I have over 5000 of these entries that need to be updated, basically something like:

But I am not sure how to do it for all entries individually, do I need some sort of loop?

Condition 1: Receipt type will always be 0 of the one where amount needs to be taken from.

Condition 2: person_id will always be identical across two of these.

Condition 3 (Optional): Only perform this update IF there is only one receipt_type = 9 (Sometimes there might be 3 or 4 entries with same person_id and being receipt_type 9

Advertisement

Answer

You can use window functions to calculate the information needed for the conditions. Then the logic is simple:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement