1

我已经看到几个类似的问题,其中包含在另一个表上按值更新表。

但是,如果 T2 拥有多个具有相同帮助的记录,并且也只更新 T1 中状态 = O 的记录?

T1
aid = 2345|Status = O
aid = 2120|Status = B


T2
aid = 2345|Status=B|Date=23/12/2002
aid = 2345|Status=F|Date=11/05/2002
aid = 2345|Status=G|Date=4/04/2002
aid = 2345|Status=R|Date=12/03/2002
aid = 2120|Status=G|Date=4/04/2012
aid = 2120|Status=R|Date=12/03/2005

例子:

 UPDATE T1
    SET T1.Status = T2.Status
    Where T1.aid = (T2.aid of the record that holds newest date or max date)
    AND = T1.Status = 'O'
4

2 回答 2

6

那么,对于 SQL Server 2005+,您可以执行以下操作:

更新

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY aid ORDER BY [Date] DESC)
    FROM Table2
)
UPDATE T1
SET T1.Status = T2.Status
FROM Table1 T1
INNER JOIN CTE T2
    ON T1.aid = T2.aid
WHERE T2.RN = 1
AND T1.Status = 'O' -- for your "updated" question

另一种方法是:

UPDATE  T1
SET     T1.Status = COALESCE(
          ( SELECT TOP (1) 
                     T2.Status
            FROM     T2
            WHERE    T2.aid = T1.aid
            ORDER BY [Date] DESC
          ), T1.Status)
FROM    T1
WHERE   T1.Status = 'O' ;
于 2013-04-03T19:55:23.453 回答
2

通常,您使用来自多个表的JOINto UPDATE,然后您可以在其自身上使用 MAX 和 JOIN 表 2:

UPDATE a
SET a.Status = b.Status
FROM T1 a 
    JOIN T2 b ON a.aid = b.aid
    JOIN (
        SELECT aid, MAX(date) maxdate
        FROM T2
        GROUP BY aid
    ) c ON b.aid = c.aid AND b.date = c.maxdate
于 2013-04-03T19:55:19.040 回答