2015-02-24 64 views
0

我想通過查看CaseID並找到第一個匹配的非空地址來填充所有的空地址。感謝您的幫助。sql查詢更新行

一些表:

IndexId CaseId Address 
------ ------- ------------ 
1   10  1 ABC STREET 
2   10  NULL 
3   10  NULL 
4   20  NULL 
5   20  100 TEST STREET 
6   20  NULL 
7   30  NULL 
8   30  NULL 
9   30  900 DEV AVENUE 

結果表:

IndexId CaseId Address 
------ ------- ------------ 
1   10  1 ABC STREET 
2   10  1 ABC STREET 
3   10  1 ABC STREET 
4   20  100 TEST STREET 
5   20  100 TEST STREET 
6   20  100 TEST STREET 
7   30  900 DEV AVENUE 
8   30  900 DEV AVENUE 
9   30  900 DEV AVENUE 
+0

你說的第一個匹配的非空地址,首先根據的是什麼? (字母,indexid等) – jarlh 2015-02-24 16:34:22

回答

1
UPDATE Table T1 
SET T1.Address = 
    (SELECT TOP 1 T2.Address FROM Table T2 
     WHERE T2.CaseId = T1.CaseId AND T2.Address IS NOT NULL) 
WHERE T1.Address IS NULL 
0

設爲首字母順序排列:

update tablename t1 set Address = (select min(Address) from tablename t2 
            where t2.CaseId = t1.CaseId) 
where Address is null 

還是第一accordning到IndexID爲:

update tablename t1 set Address = (select top 1 Address from tablename t2 
            where t2.CaseId = t1.CaseId 
            and ADDRESS IS NOT NULL 
            order by indexid) 
where Address is null 

編輯:錯過不是在子查詢中爲空,謝謝TZHX。

0

假設表被稱爲@t:

SELECT t1.* 
FROM @t AS t1 
    LEFT JOIN @t AS t2 ON t2.CaseID = t1.CaseID 
WHERE t1.Address is not null