使用COALESCE功能编程

时间:2012-07-05 05:56:49

标签: sql sql-server

我有一张这样的表

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

问题在于,它应该在帐户级别重复以前的文本。如图所示,'xyx' 1的ac值重复到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级写了一个循环。但它正在扼杀性能。任何人都可以提出一个出路。谢谢你。

1 个答案:

答案 0 :(得分:4)

这有效:

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。但是,TBH,无论如何,这对于手头的工作来说都是错误的工具。您可以重新编写上面的查询以使用COALESCE,并让它更新所有行而不仅仅是那些NULL值的行,但我想不出有任何合理的理由。< / p>