sql查询更新行

时间:2015-02-24 16:32:20

标签: sql sql-server-2008

我试图通过查看CaseID来填充所有空地址,并找到第一个匹配的非空地址。谢谢你的帮助。

一些表格:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

按字母顺序设置:

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

或者首先根据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

编辑:在子查询中,miss不是null,谢谢THX。

答案 2 :(得分:0)

假设该表名为@t:

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