2012-09-28 47 views
0

我創建了一個臨時表#tbl(account,last_update)。我有兩個來自不同數據源的插入(可能是來自不同數據庫的表)插入具有上次更新日期的帳戶。例如如何有條件地插入

create table #tbl ([account] numeric(18, 0), [last_update] datetime) 

insert into #tbl(account , last_update) 
select table1.account, max(table1.last_update) 
from table1 join… 
group by table1.account 

insert into #tbl(account , last_update) 
select table2.account, max(table2.last_update) 
from table2 join… 
group by table2.account 

問題是這可能會導致表#tbl中的重複帳戶。每次插入時我都必須避免它,或者在插入後刪除重複項。另外,如果有兩個不同的last_update帳戶,我希望#tbl擁有最新的last_update。我如何實現這個條件插入?哪一個會有更好的表現?

+0

是否每個帳戶只有兩次INSERT?你是否只爲每個賬戶運行一次,或者你能在第二天還是一週後再運行一次?你檢查了['MERGE'](http://technet.microsoft.com/en-us/library/bb510625(v = sql.100).aspx)命令嗎? – Pondlife

回答

1

你認爲你可以查詢改寫爲這樣的:

create table #tbl ([account] numeric(18, 0), [last_update] datetime) 

insert into #tbl(account , last_update) 
    select theaccount, MAX(theupdate) from 
    (
    select table1.account AS theaccount, table1.last_update AS theupdate 
    from table1 join… 
    UNION ALL 
    select table2.account AS theaccount, table2.last_update AS theupdate 
    from table2 join… 
    ) AS tmp GROUP BY theaccount 

的UNION ALL將爲你創造獨特的1分結合表1 +表2的記錄。從那裏開始,您可以像是普通表一樣使用,這意味着您可以使用「group by」查找每個記錄的最大last_update

+0

對不起,我更新了答案,糾正了嚴重的錯別字。 – mbarthelemy

+0

我仍然在組附近得到語法錯誤 – GLP

+0

@GaolaiPeng它是「GROUP BY theaccount」,而不是「GROUP BY帳戶」,你可以重試嗎? – mbarthelemy

0
 insert into #tbl(account , last_update) 
    select account, last_update 
    from 
     (
    select a.* from #table1 a where 
    last_update in(select top 1 last_update from #table1 b 
     where 
     a.account = b.account 
     order by last_update desc) 
     UNION 
    select a.* from #table2 a where 
    last_update in(select top 1 last_update from #table2 b 
     where 
     a.account = b.account 
     order by last_update desc) 
    ) AS tmp