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。我如何实现这个条件插入?哪一个会有更好的表现?

4

2 回答 2

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 个结合 table1 + table2 记录的唯一表。从那里,您可以像普通表一样行事,这意味着您可以使用“分组依据”找到每条记录的最大 last_update

于 2012-09-28T20:19:39.553 回答
0
插入 #tbl(account , last_update)
  选择帐户,last_update
     从
      (
    select a.* from #table1 a where
     last_update in(从 #table1 b 中选择前 1 个 last_update
      在哪里
        a.account = b.account
         按 last_update 顺序排序)
         联盟
    select a.* from #table2 a where
     last_update in( select top 1 last_update from #table2 b
      在哪里
        a.account = b.account
         按 last_update 顺序排序)
      ) 作为 tmp
于 2012-09-30T13:27:52.767 回答