简体   繁体   中英

SQL update missing values from same table

If I have this table

----------  ----------  
jones       new york  
jones                   
richard     seattle
jones                  
richard                
Ellen       Vancouver
Ellen                  

And I want this new table

----------  ----------  
jones       new york  
jones       new york            
richard     seattle
jones       new york           
richard     seattle           
Ellen       Vancouver
Ellen       Vancouver           

How can I update it? I am using Postgresql.

The best solution would be to properly normalize the tables such that a one to one join table was created between them which joins each name to a single city, if indeed there should be exactly one city per name.

Given what you have though, you may supply a subquery in the FROM clause which returns the MAX(city) per name group. From there the SET clause updates the main table's city to the value returned by the subquery.

UPDATE 
  tbl t
SET
  city = c.city
FROM
  /* Subquery in FROM returns first (max()) non-null city per name */
  (SELECT name, MAX(city) AS city FROM tbl WHERE city IS NOT NULL GROUP BY name) c
WHERE 
  /* Only update non-null cities */
  t.city IS NULL
  /* Here's the joining relation to the subquery */
  AND t.name = c.name;

Here's a demo: http://sqlfiddle.com/#!1/6ad17/1

Here is a solution with a temp table that works. You should be able to apply the same logic to your issue.

create temp table foo(employee_name text, city text);

insert into foo (employee_name, city) values
('jones', 'new york'),
('jones', NULL),
('richard', 'seattle'),
('richard', NULL),
('ellen', 'vancouver'),
('ellen', NULL);

update foo f set city = x.city
from foo x 
where f.employee_name = x.employee_name
and f.city is null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM