代码之家  ›  专栏  ›  技术社区  ›  aviss

SQL Server:通过匹配不同列中的值,将空值替换为来自同一列的值

  •  0
  • aviss  · 技术社区  · 6 年前

    我在SQL Server中有一个表,在“date”列中有一些空值:

    platform   date         id
    ---------------------------
    web        2018-10-10   1
    mob                     1
    mob                     1
    web        2018-10-15   2
    mob                     2
    ntl        2018-10-09   3
    web        2018-10-12   3
    web        2018-10-11   4
    mob                     3
    

    platform   date         id
    ---------------------------
    web        2018-10-10   1
    mob        2018-10-10   1
    mob        2018-10-10   1
    web        2018-10-15   2
    mob        2018-10-15   2
    ntl        2018-10-09   3
    web        2018-10-12   3
    web        2018-10-11   4
    mob        2018-10-12   3
    

    5 回复  |  直到 6 年前
        1
  •  2
  •   Gordon Linoff    6 年前

    您可以使用可更新的CTE:

    with toupdate as (
          select t.*, max(date) over (partition by id) as max_date
          from t
         )
    update toupdate
        set date = max_date
        where date is null;
    
        2
  •  0
  •   GGadde    6 年前
    update a
    SET a.date = b.date
    from #test AS a
    INNER JOIN (SELECT * FROM #test WHERE platform = 'web') as b on a.id = b.id
    WHERE a.date is null
    

    更新表名 #test 根据需要。

        3
  •  0
  •   S3S    6 年前

    相关的子查询应该可以工作

    declare @table table (platform char(3), [date] date, id int)
    insert into @table
    values
    ('web','2018-10-10',1),
    ('mob',null,1),
    ('mob',null,1),
    ('web','2018-10-15',2),
    ('mob',null,2),
    ('ntl','2018-10-09',3),
    ('web','2018-10-12',3),
    ('web','2018-10-11',4),
    ('mob',null,3)
    
    update @table
    set date = (select max(date) from @table t2 where t2.id = [@table].id)
    where [@table].date is null  
    
    select * from @table
    
        4
  •  0
  •   zkemppel    6 年前

    我不建议给专栏命名 date

    UPDATE a
    SET [date] = b.[date]
    FROM MyTable a
    INNER JOIN MyTable b ON a.id = b.id and b.platform = 'web'
    WHERE a.platform = 'mob' AND a.[date] IS NULL
    

    enter image description here

        5
  •  0
  •   Ilyes    6 年前

    你可以这样做

    UPDATE T
    SET [Date] = D
    FROM
    (
        SELECT ID, MAX([Date]) AS D
        FROM T
        WHERE [Date] IS NOT NULL
        GROUP BY ID
    ) TT INNER JOIN T ON T.ID = TT.ID
    WHERE T.[Date] IS NULL;
    

    db<>fiddle demo