0

Given a table like below. I want to move and add all values from the column escrow1 to balance1 of it's corresponding uid. And likesise for escrow2 to balance2. So in the case below. The row with uid 4 will have a balance of 1858000+42000, row with uid 3 will have a balance1 = 1859265+30735 and escrow1 = 0, and row with uid 2 will have a balance2 = 940050+1050000 and escrow2 = 0. Everything else is the same. Is it possible to do this in one query? I've been trying hard, but I can't come up with a solution, so I might have to do it in a function and loop all the rows, but I would prefer not to. Also I know that only a small amount of rows will have escrow values not equal to 0. Given that, is there a way to optimize the query?

 uid | balance1 | escrow1 | balance2 | escrow2 
-----+----------+---------+----------+---------
   1 |     5000 |       0 |        0 |       0
   9 |     5000 |       0 |        0 |       0
   6 |  1900000 |       0 |  1899960 |       0
   5 |  1900000 |       0 |  1900000 |       0
   7 |  1900000 |       0 |  1900000 |       0
   8 |  1900000 |       0 |  1900000 |       0
   4 |  1858000 |   42000 |  1900014 |       0
   2 |  1910000 |       0 |   940050 | 1050000
   3 |  1859265 |   30735 |  1895050 |       0

2 Answers 2

3

If you just want to select the data from the table use the query provided by Greg. If you want to update the table itself, the below query can help.

Update TABLENAME
     Set Balance1 = Balance1 + Escrow1,
         Balance2 = Balance2 + Escrow2,
         Escrow1 = 0, Escrow2 = 0

Hope this helps.

0

I think it's as simple as:

SELECT uid
      ,Balance1 + Escrow1 AS Balance1
      ,Balance2 + Escrow2 AS Balance2
FROM   TableName

In terms of optomising, I haven't done much with Postgre, but I doubt you'd need to do any optimizing (assuming you have proper primary key, etc. on the table)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.