How can I update this table (SCORE col):
x
name date DIV SCORE
------ ----------- ----- ----
TOM 2000-01-01 A 20
TOM 2000-01-01 B 30
TOM 2000-01-01 C 200
TOM 2000-01-03 A 10
TOM 2000-01-03 B 40
TOM 2000-01-03 C 300
JACK 2000-01-01 C 500
JACK 2000-01-01 B 100
JACK 2000-01-01 A 200
JACK 2000-12-01 C 300
JACK 2000-12-01 B 50
JACK 2000-12-01 A 100
To:
name date DIV SCORE
------ ----------- ----- ----
TOM 2000-01-01 A 20
TOM 2000-01-01 B 30
TOM 2000-01-01 C 150(=200-20-30)
TOM 2000-01-03 A 10
TOM 2000-01-03 B 40
TOM 2000-01-03 C 250(=300-10-40)
JACK 2000-01-01 C 200(=500-100-200)
JACK 2000-01-01 B 100
JACK 2000-01-01 A 200
JACK 2000-12-01 C 150(=300-50-100)
JACK 2000-12-01 B 50
JACK 2000-12-01 A 100
C-=A+B
Advertisement
Answer
In most databases you can use a correlated subquery:
update t
set score = (score -
(select coalesce(sum(score), 0)
from t t2
where t2.name = t.name and t2.date = t.date and
t2.div in ('A', 'B')
)
)
where div = 'C';
There are other ways to phrase this, but those are database-dependent.