Reputation: 2397
I have a table, SUBSCRIBERS
, in which I can have more than one entry per subscriber.
(let's say because it stopped being a subscriber and now it became a customer again, so it has a different 'identity' but the same 'subno')
I need an UPDATE
statement that updates a column in a row (let's say their address), but only for the latest record for that subscriber (with the latest EffectiveDate
).
So I figured out how to select such a row:
SELECT
t1.identity, t1.Subno, t1.EffectiveDate
FROM
SUBSCRIBERS t1
INNER JOIN
(SELECT subno,max(EffectiveDate) as LatestDate
FROM SUBSCRIBERS
GROUP BY Subno) t2 ON t1.Subno = t2.Subno AND t1.EffectiveDate = t2.LatestDate
But I don't know how to UPDATE the row for a given subno value. Well, I do, but I don't want to do it with 17 nested select statements.
Thanks!
Upvotes: 1
Views: 3684
Reputation: 7214
You can use 'Update from' :
UPDATE SUBSCRIBERS
SET Address = 'the address'
FROM SUBSCRIBERS t1
INNER JOIN
(SELECT subno,max(EffectiveDate) as LatestDate FROM SUBSCRIBERS
GROUP BY Subno) t2
ON t1.Subno = t2.Subno and t1.EffectiveDate = t2.LatestDate
Upvotes: 4