2012-07-05 36 views
2

我有這樣編程與COALESCE功能

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'值爲ac 1重複爲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級別寫了一個循環。但它正在殺死性能。任何人都可以請suggenst出路。非常感謝。

+3

表格具有* no *固有順序。你很幸運,在這個小樣本的情況下,它會發生*甚至接近你想要的更新。我們需要的第一件事是我們可以定義一個訂單的列,通過它我們可以確定哪些行先於其他行。 –

+0

@Damien嗨,我確實有datetime referecne coumn.I更新了我的示例表。我的實際表有數百萬條記錄。在將數據傳遞給Coalesce函數之前,我將按日期時間列對數據進行排序。 – Gokul

+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值的那些行,但我想不出任何理由這麼做。

+0

@Demien非常感謝您的解決方案。我不得不改變標題,但保持不變,以便這篇文章可以顯示替代。 – Gokul