2014-06-16 194 views
0

我有一个SQL表需要使用另一个表中的数据更新。
这似乎是一个非常简单的查询,但我无法更新我的表。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的日期?

回答

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 
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) 
+0

我没有投票下你的答案 –

+0

没问题,两个答案似乎是合理的,选择适合你的人。使用显示执行计划来查看一种方法与另一种方法是否存在边缘。查询优化器倾向于更频繁地解决问题,然后不是。 –