1

このテーブルがあれば

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

そして、私はこの新しいテーブルが欲しい

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

どうすれば更新できますか? Postgresql を使用しています。

4

2 に答える 2

1

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

于 2013-06-11T16:48:09.763 に答える