gpt4 book ai didi

sql - 使用 COALESCE 函数编程

转载 作者:行者123 更新时间:2023-12-02 05:38:27 24 4
gpt4 key购买 nike

我有一张这样的 table

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

我必须通过重复前面的文本来删除空值,所以我写了

Declare @asgc nvarchar(10)
UPDATE coalescetest
SET
@asgc = COALESCE(asgc, @asgc),
asgc = COALESCE(asgc, @asgc)

这段代码给了我下面的输出

ac  asg     asgc
1 abc abc
1 NULL abc
1 xyz xyz
1 NULL xyz
2 NULL xyz
2 lmn lmn
2 NULL lmn

这里的问题是,它应该在帐户级别重复以前的文本。正如所见,ac 1 的 'xyx' 值重复到 ac 2。这不应该发生。理想的输出应该是这样的

ac  asg     asgc
1 abc abc
1 NULL abc
1 xyz xyz
1 NULL xyz
2 NULL NULL
2 lmn lmn
2 NULL lmn

因此,我在 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

结果:

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

请注意,在任何时候,我都不会依赖什么命令将 UPDATE 实际应用于表。


刚意识到我的回答当然没有按照问题的标题使用 COALESCE。但是,老实说,无论如何,这对于手头的工作来说都是错误的工具。您可以重写上面的查询以使用 COALESCE,并让它更新所有行,而不仅仅是那些具有 NULL 值的行,但我想不出任何理智的这样做的理由。

关于sql - 使用 COALESCE 函数编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11338514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com