简体   繁体   English

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

[英]SQL Server : replace Null values with values from the same column by matching values in a different column

I have a table in SQL Server with some null values in column "date": 我在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

I want to update null values in 'date' for 'mob' platform by matching the 'id' column from platform 'web'. 我想通过匹配平台“ web”中的“ id”列来更新“ mob”平台的“日期”中的空值。 The result should look like this: 结果应如下所示:

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

Will really appreciate your help! 会非常感谢您的帮助!

You can use an updatable CTE: 您可以使用可更新的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;

A correlated subquery should work 相关的子查询应该工作

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

I would not recommend naming a column date as it's a reserved word, but this will give you the desired result assuming there is only 1 web entry per id. 我不建议命名列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

在此处输入图片说明

You can do like 你可以喜欢

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 db <> fiddle演示

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

Update the tablename #test as needed. 根据需要更新表名#test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM