在包含多个记录的其他表中按值更新表

时间:2013-04-03 19:48:57

标签: sql-server

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

但是如果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'

2 个答案:

答案 0 :(得分: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' ;

答案 1 :(得分:2)

通常,您从多个表中使用JOINUPDATE,然后您可以使用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