使用join和MAX函数的UPDATE表

时间:2015-07-28 04:36:39

标签: sql-server join

我有两张桌子t1& T2

表t1

+---------------------------------------------------------------+
|   RequestID       dateCreated               dateSolProvided   |
+---------------------------------------------------------------+
| 100         4/1/2015 11:31:36 AM         4/1/2015 11:04:04 AM |
+---------------------------------------------------------------+

这里dateSolProvided应该大于dateCreated。

表t2

+-----------------------------------------------------------+
| RequestID    RequestDetailID         SolutionProvidedDate |
+-----------------------------------------------------------+
| 100            123456                4/1/2015 11:04:04 AM |
| 100            678910                4/1/2015 11:41:56 AM |
+-----------------------------------------------------------+

现在我的问题是,我必须更新表t1 - > dateSolProvided 基于表t2的SolutionProvidedDate的最大

所以解决方案应该是(对于表t1):

+---------------------------------------------------------------+
|   RequestID       dateCreated               dateSolProvided   |
+---------------------------------------------------------------+
| 100         4/1/2015 11:31:36 AM         4/1/2015 11:41:56 AM |
+---------------------------------------------------------------+

如何使用连接更新这两个表并一起使用MAX函数?

1 个答案:

答案 0 :(得分:0)

您可以使用相关子查询:

UPDATE t1
    SET dateSolProvided = ( SELECT TOP 1 SolutionProvidedDate
                            FROM Table2
                            WHERE RequestID = t1.RequestID
                            ORDER BY SolutionProvidedDate DESC
                          )
FROM Table1 t1
WHERE dateSolProvided < dateCreated