postgres - 根据其他行更新行

时间:2016-09-06 21:06:00

标签: sql postgresql sql-update

我想知道,如何基于其他行的值更新某些列为空的行。

enter image description here

我想更新第一行的列(user_name,database_name,connection_from),其中包含以下两行中的值。 session_id是相同的。

感谢。

1 个答案:

答案 0 :(得分: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);
相关问题