我创建了一个临时表#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 :(得分: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将为您构建一个结合table1 + table2记录的唯一表。从那里,你可以表现得像一个普通的表,这意味着你可以使用“group by”找到每个记录的最大last_update
答案 1 :(得分: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