tags:

views:

61

answers:

3

SQL syntax question about UPDATE. It would be much easier to ask the question by giving example below:

**Payments Table**

ID  user_id  payment_due   payment_made 
1      3        10.0           5.0
1      3        10.0           10.0
1      9        20.0           20.0



**Balance Table**

ID  user_id    current_balance 
1      3            ???
2      9            ???

Let say I would like to update the current balance for specific user. What would be the correct and efficient SQL syntax to add all payment dues and subtract it from all payment made for a specific user?

In this case, current_balance for user '3' is 5.0 and for user '9' is 0.0

+2  A: 

How about:

select
   ID,
   user_id,
   (sum(payment_due) - sum(payment_made)) current_balance
from
   PaymentsTable

group by
   ID,
   user_id
Ron Savage
This might be the best approach. Don't keep a `Balance` table since the balance would constantly change. You could even turn this query into a view so that it behaves like the `Balance` table.
cmptrgeekken
Or use a trigger to keep the data in sync.
Frank Heikens
as stated above don't keep a Balance table...storing a calculated field (current_balance) breaks the rules of normalization, use the query to get the data on the fly
Leslie
Thanks all for the suggestions. I think it is best not to use current balance table
Cory T.
+1  A: 

You need to use a subquery. Something like this should work:

UPDATE
    balance_table b
SET
    current_balance = (SELECT
            SUM(payment_due - payment_made)
        FROM
            payments_table p
        WHERE
            p.user_id = b.user_id)
Tatu Ulmanen
+2  A: 

To update your table, use a sub-query:

UPDATE Balance_Table b
SET current_balance =
  ( SELECT SUM( payment_due - payment_made )
    FROM Payments_Table p
    WHERE p.user_id = b.user_id
  )

Think about the update-approach though. Your Balance_Table will be out of sync as soon as Payments_Table changes, so you might be better off with actually selecting data from there.

Peter Lang
I suppose he could throw this UPDATE statement in a trigger on the `Payments` table. That would remove some of the discrepancy.
cmptrgeekken
@cmptrgeekken: Using a trigger would be possible. If there are lots of records in `Payments_Table` but only few records change and results of `Balance_Table` are queried often, then this could be the right approach. Otherwise, just summing up `Payments_Table` would be the easier approach.
Peter Lang