我有这样的桌子
ac asg asgc asgdt
1 abc abc 2012-06-01 00:00:00.000
1 NULL NULL 2012-06-02 00:00:00.000
1 xyz xyz 2012-07-01 00:00:00.000
1 NULL NULL 2012-07-02 00:00:00.000
2 NULL NULL 2012-07-03 00:00:00.000
2 lmn lmn 2012-08-01 00:00:00.000
2 NULL NULL 2012-08-02 00:00:00.000
Run Code Online (Sandbox Code Playgroud)
我必须通过重复前面的文本来删除空值,所以我写了
Declare @asgc nvarchar(10)
UPDATE coalescetest
SET
@asgc = COALESCE(asgc, @asgc),
asgc = COALESCE(asgc, @asgc)
Run Code Online (Sandbox Code Playgroud)
这段代码给了我下面的输出
ac asg asgc
1 abc abc
1 NULL abc
1 xyz xyz
1 NULL xyz
2 NULL xyz
2 lmn lmn
2 NULL lmn
Run Code Online (Sandbox Code Playgroud)
问题是,它应该在帐户级别重复上一个文本。如图所示,'xyx'将ac1的值重复为ac2。这不应该发生。理想的输出应该是这样的
ac asg asgc
1 abc abc
1 NULL abc
1 xyz xyz
1 NULL xyz
2 NULL NULL
2 lmn lmn
2 NULL lmn
Run Code Online (Sandbox Code Playgroud)
因此,我在ac级别上编写了一个循环。但这会破坏性能。任何人都可以建议出路。非常感谢。
这有效:
declare @tab table (ac int not null, asg char(3) null, asgc char(3) null, asgdt datetime not null)
insert into @tab(ac,asg,asgc,asgdt) values
(1,'abc','abc','2012-06-01 00:00:00.000'),
(1,NULL,NULL,'2012-06-02 00:00:00.000'),
(1,'xyz','xyz','2012-07-01 00:00:00.000'),
(1,NULL,NULL,'2012-07-02 00:00:00.000'),
(2,NULL,NULL,'2012-07-03 00:00:00.000'),
(2,'lmn','lmn','2012-08-01 00:00:00.000'),
(2,NULL,NULL,'2012-08-02 00:00:00.000')
update
t1
set
asgc = t2.asgc
from
@tab t1
inner join
@tab t2
on
t1.ac = t2.ac and --Belong to same account
t2.asgc is not null and --Has a useful value
t2.asgdt < t1.asgdt --Is an earlier row
left join
@tab t3
on
t1.ac = t3.ac and --Belong to same account
t3.asgc is not null and --Has a useful value
t3.asgdt < t1.asgdt and --Is an earlier row
t3.asgdt > t2.asgdt --But occurs later than t2
where
t1.asgc is null and --Needs a fill-in value
t3.ac is null --And no better matching row was found for the replacement
select * from @tab
Run Code Online (Sandbox Code Playgroud)
结果:
ac asg asgc MysteriousUnamedColumn
----------- ---- ---- -----------------------
1 abc abc 2012-06-01 00:00:00.000
1 NULL abc 2012-06-02 00:00:00.000
1 xyz xyz 2012-07-01 00:00:00.000
1 NULL xyz 2012-07-02 00:00:00.000
2 NULL NULL 2012-07-03 00:00:00.000
2 lmn lmn 2012-08-01 00:00:00.000
2 NULL lmn 2012-08-02 00:00:00.000
Run Code Online (Sandbox Code Playgroud)
需要注意的是,在任何时候,我是依靠什么命令UPDATE实际应用到表。
只是意识到,按照问题的标题,我的答案当然实际上并没有使用 COALESCE。但是,TBH无论如何都是错误的工具。您可以使用重写上面的查询COALESCE,并让它更新所有行而不是仅更新具有NULL值的行,但是我想不出任何明智的理由。