我有一个表格,字段为Id1
,ID2
,Points1
,Points2
。我有另一个包含Id1
,Id2
,Address1
,address2
,city 1
,city2
,state1
列的表, state2
。我必须根据第二个表中有多少列填充来更新pointsA
和PointsB
列,这意味着它们没有空值。实施例
表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中实现这一目标?
由于
答案 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