根据另一个表中的计数器更新列?

时间:2012-03-30 22:48:45

标签: sql sql-server-2008

我有一个表格,字段为Id1ID2Points1Points2。我有另一个包含Id1Id2Address1address2city 1city2state1列的表, state2。我必须根据第二个表中有多少列填充来更新pointsAPointsB列,这意味着它们没有空值。实施例

表1

ID1  ID2   Points 1 Points2
1     2     2         0

表2

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

如何在sql server 2008中实现这一目标?

由于

1 个答案:

答案 0 :(得分:1)

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
相关问题