SQL查询:基于第2列中的值用第1列中的其他值填充空白/空值

时间:2020-06-12 19:36:44

标签: sql

我需要有关SQL查询的帮助。我有一个表,其中某些值在列中缺失。我想根据column1的值填充缺失的值

-----Col_1-------Col_2------
    12345         Value 1
    12345         
    12345
    54321         Value 2
    54321         
    54321         
------------------------------

输出应该是这样的。

-----Col_1-------Col_2------
    12345         Value 1
    12345         Value 1
    12345         Value 1
    54321         Value 2
    54321         Value 2
    54321         Value 2
------------------------------

2 个答案:

答案 0 :(得分:0)

尝试这样的事情;

CASE 
   WHEN x IS NULL 
   THEN ( SELECT y from a WHERE y = y AND y IS NOT NULL)
   ELSE x
END 

答案 1 :(得分:0)

您可以使用窗口功能:

select col_1, max(col_2) over (partition by col_1)
from t;

这将给给定col_1的所有行分配相同的值。如果您想保留现有值,即使它们不匹配:

select col_1, coalesce(col_2, max(col_2) over (partition by col_1))
from t;

如果要更新值:

update t
    set col_2 = (select t2.col2 from t t2 where t.col_1 = t2.col_1 and t2.col_2 is not null fetch first 1 row only)
    where col_2 is null;