SQL Server:通过匹配不同列中的值,用同一列中的值替换Null值

时间:2018-10-18 20:11:41

标签: sql sql-server

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

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

我想通过匹配平台“ web”中的“ id”列来更新“ mob”平台的“ date”中的空值。结果应如下所示:

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 个答案:

答案 0 :(得分:2)

您可以使用可更新的CTE:

   message.setHeader("Reply-To",replyTo.trim());

答案 1 :(得分:0)

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

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)

我不建议将列date命名为保留字,但是假设每个id仅有1个Web条目,这将为您提供所需的结果。

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

答案 3 :(得分:0)

你可以喜欢

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

答案 4 :(得分:0)

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