2014-06-16 165 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

沒問題,兩個答案似乎是合理的,選擇適合你的人。使用顯示執行計劃來查看一種方法與另一種方法是否存在邊緣。查詢優化器傾向於更頻繁地解決問題,然後不是。 –