SQL Update Table查询无效

时间:2014-06-16 16:11:45

标签: sql sql-server sql-update

我有一个SQL表需要使用另一个表中的数据进行更新 这似乎是一个非常简单的查询,但我无法更新我的表。

CustID      FirstCommunicationDate  SecondCommunicationDate
20144       2013/02/01      2013/02/16
20156       2013/02/10      2013/02/16
20755       2013/02/09      2013/02/16
20814       2013/04/14      2013/02/16
20903       2013/06/12      2013/02/16
21333       2013/06/21      2013/02/16


CustID      CommunicationNum    CommunicationDate
20144       1           2013/02/16
20144       1           2013/03/13
20144       2           2013/04/18
20903       1           2013/02/12
20903       1           2013/03/19
20903       2           2013/04/04
21333       1           2013/02/16
21333       1           2013/02/22
21333       2           2013/04/29

我的更新查询是:

UPDATE tblCommunication
SET FirstCommunicationDate = (SELECT MAX(CommunicationDate)
                FROM FieldData fd
                WHERE CustID = fd.CustID
                AND fd.CommunicationNum = 1)
WHERE CustID IN (SELECT CustID FROM FieldData)

我正在寻找的结果是:

CustID      FirstCommunicationDate  SecondCommunicationDate
20144       2013/03/13      2013/02/16
20903       2013/03/19      2013/02/16
21333       2013/02/22      2013/02/16

如何更新tblCommunication中的日期?

2 个答案:

答案 0 :(得分:1)

update a
set a.FirstCommunicationDate = b.MaxDate
from tblCommunication as a
inner join (select 
                CustID
                ,MAX(CommunicationDate) as MaxDate
            from FieldData
            where CommunicationNum = 1
            group by CustID) as b
    on a.CustID = b.CustID

答案 1 :(得分:0)

试试这个

UPDATE tblCommunication
SET FirstCommunicationDate = (SELECT MAX(CommunicationDate)
                FROM FieldData fd
                WHERE t.CustID = fd.CustID
                AND fd.CommunicationNum = 1)
FROM tblCommunication t
WHERE t.CustID IN (SELECT CustID FROM FieldData)