user252980
user252980

Reputation: 3

sql update query

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/2009
    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

Upvotes: 0

Views: 168

Answers (2)

user240709
user240709

Reputation: 207

-- 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

Upvotes: 0

Samuel
Samuel

Reputation: 2490

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

Upvotes: 1

Related Questions