0

我有两张桌子:

events

mac | na
----------
abc | (null)
abc | (null)
def | (null)

enrichments

mac | na  | timestamp
---------------------
abc | na1 | 1
abc | na2 | 2
abc | na3 | 3
def | na4 | 1

现在我想events.na用 中的值更新列enrichments.na,其中mac匹配,并且是那个特定timestamp的最大值。timestampmac

对于此示例,结果将是:

abc | na3
abc | na3
def | na4

最有效的方法是什么?

谢谢!

4

2 回答 2

1

这应该适用于使用公用表表达式的 SQL Server

create table events (mac nvarchar(3), na nvarchar(3))
insert into events values ('abc',null);
insert into events values ('abc',null);
insert into events values ('def',null);

create table enrichments (mac nvarchar(3), na nvarchar(3), timestamp int)
insert into enrichments values ('abc','na1',1)
insert into enrichments values ('abc','na2',2)
insert into enrichments values ('abc','na3',3)
insert into enrichments values ('def','na4',1)

with latestEnrichment (mac, latestTimestamp) as
    (select mac, MAX(timestamp)
    from    enrichments
    group by mac)
update  events
set     na = en.na
from    events e join enrichments en on e.mac = en.mac
        join latestEnrichment le on en.timestamp = le.latesttimestamp and
        en.mac = le.mac
于 2012-04-17T08:45:01.597 回答
1
UPDATE events AS e
SET na = 
    ( SELECT n.na
      FROM enrichments AS n
      WHERE n.mac = e.mac
      ORDER BY n.timestamp DESC
      FETCH FIRST 1 ROWS ONLY
    ) 
于 2012-04-17T09:16:52.163 回答