开发者

sql update query

开发者 https://www.devze.com 2022-12-16 13:21 出处:网络
I need an update query to set the null values with another value in the same group for example Table filed1filed2filed3

I need an update query to set the null values with another value in the same group

for example

 Table
    filed1   filed2      filed3
    1          e         1/1/2009
    1          e         null
    1          e         1/1/2009
    2          f         2/2/2009
    2          f         2/2/开发者_如何学JAVA2009
    2          f         null
    3          g         3/3/2009
    3          g         null

Expected Result

filed1   filed2      filed3
1          e         1/1/2009
1          e         1/1/2009
1          e         1/1/2009
2          f         2/2/2009
2          f         2/2/2009
2          f         2/2/2009
3          g         3/3/2009
3          g         3/3/2009


Which database server are you using? In Oracle, this could work, assumming filed3 is equal for every row in the group or null:

EMPI@XE > select * from sov;

    FILED1 F FILED3
         1 e
         1 e 1/1/2009
         1 e 1/1/2009
         2 g 1/2/2009
         2 g 1/2/2009
         2 g

EMPI@XE > update sov s
  2    set
  3        s.filed3 =
  4            (select filed3
  5               from sov so
  6               where so.filed1 = s.filed1
  7                        and so.filed2 = s.filed2
  8                        and so.filed3 is not null
  9                    and rownum = 1)
 10   where filed3 is null;

EMPI@XE > select * from sov;

    FILED1 F FILED3

         1 e 1/1/2009
         1 e 1/1/2009
         1 e 1/1/2009
         2 g 1/2/2009
         2 g 1/2/2009
         2 g 1/2/2009


-- note table1 is your table

UPDATE t1 set t1.filed3 = t2.filed3 
from table1 t1, table1 t2
where t1.filed3 is null
and t2.filed3 is not null 
and t1.filed2 = t2.filed2 and 
t1.filed1 = t2.filed1
0

精彩评论

暂无评论...
验证码 换一张
取 消