2016-09-06 54 views
0

我在想,如何根據其他行的值更新某些列爲空的行。postgres - 基於其他行更新一行

enter image description here

我想在下面的兩行的值更新第一行的列(USER_NAME,數據庫名稱,connection_from)。 session_id是相同的。

謝謝。

+0

這樣做的關鍵部分是理解數據,你試圖收集,不更新本身。如果你想知道如何選擇你需要的數據,UPDATE很簡單。不知道表定義的細節(特別是主鍵),我不能更具體。 順便說一句,您應該考慮將連接信息存儲爲connection_ip inet和connection_port int; inet類型爲您提供了一些強大的運算符。 –

回答

0

對於如何選擇要更新的值,您的問題相當模糊。讓我假設你正在尋找基於session_id的數據和任何非NULL值將這些三列的工作:

update t 
    set user_name = coalesce(t.user_name, tt.user_name), 
     database_name = coalesce(t.database_name, tt.database_name), 
     connection_from = coalesce(t.connection_from, tt.connection_from) 
    from (select session_id, max(user_name) as user_name, 
       max(database_name) as database_name, 
       max(connection_from) as connection_from 
      from t 
      group by session_id 
     ) tt 
    where t.session_id = tt.session_id and 
      (t.user_name is null or t.database_name is null or t.connection_from is null); 
+0

非常感謝。幾乎工作。 connection_from列未更新。一個小漁獲。 connection_from列雖然看起來像空,當我發出select * from t其中connection_from爲null時,沒有行被返回。你能指導我嗎?再次感謝。 – vignesh28

+0

@ vignesh28。 。 。用'case when t.connection_from>''然後t.connection_from else tt.connection_from end''替換'coalesce()''。 –