2

このようなテーブルがあります

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

ここでの問題は、アカウント レベルで前のテキストを繰り返す必要があることです。ご覧のとおり、1 の'xyx'値が2acに繰り返されますac。これは発生しないはずです。理想的な出力は次のようになります

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それで、レベルでループを書きました。しかし、それはパフォーマンスを殺しています。誰でも抜け道を提案できますか。事前に感謝します。

4

1 に答える 1

5

これは機能します:

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 さん、いずれにせよ、それは当面の仕事には不適切なツールでした。上記のクエリを書き直して a を使用しCOALESCE、値を持つ行だけでなくすべての行を更新するNULLこともできますが、そうする正当な理由は思いつきません。

于 2012-07-05T06:18:25.643 に答える