user1304271
user1304271

Reputation: 23

Update a column based on counter from another table?

I have a table the fields are Id1, ID2, Points1, Points2. I have another table that has the columns Id1, Id2, Address1, address2, city 1, city2, state1, state2. I have to update the pointsA and PointsB column based on how many of the columns in the second table are filled meaning they dont have null. Ex

Table 1

ID1  ID2   Points 1 Points2
1     2     2         0

Table 2

ID1  ID2 Address1 address2 city 1 city2 state1 state2.
1    2    a1       null     null   null  s1     null

How can I achieve this in sql server 2008?

Thanks

Upvotes: 0

Views: 157

Answers (1)

Michael Fredrickson
Michael Fredrickson

Reputation: 37388

UPDATE t1
SET 
    Points1 = t2.Points1, 
    Points2 = t2.Points2
FROM
    Table1 t1 JOIN (
    SELECT
        ID1,
        ID2,
        CASE WHEN Address1 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN City1 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN State1 IS NULL THEN 0 ELSE 1 END AS Points1,
        CASE WHEN Address2 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN City2 IS NULL THEN 0 ELSE 1 END +
        CASE WHEN State2 IS NULL THEN 0 ELSE 1 END AS Points2,
    FROM Table2
) t2 ON t1.ID1 = t2.ID1 AND t1.ID2 = t2.ID2

Upvotes: 1

Related Questions