使用单独查询中的值更新new

时间:2016-02-04 22:10:19

标签: sql-server

我有这个查询返回id和int值列表

SELECT
Opportunity.opportunityid
,obn.cnt
FROM Opportunity
LEFT JOIN Account
ON Opportunity.AccountId = Account.AccountId
OUTER APPLY 
(SELECT
    COUNT(dst) AS cnt
FROM [server].[telecoms].[dbo].[vwOpportunityUpdate]
WHERE dst COLLATE DATABASE_DEFAULT = REPLACE(Account.Telephone1,' ','') COLLATE DATABASE_DEFAULT
AND calldate > opportunity.createdon
GROUP BY dst) obn
WHERE DATEDIFF(dd,Opportunity.CreatedOn,GETDATE()) < 30
AND obn.cnt IS NOT NULL

我需要做的就是根据这些结果中的值更新表格

UPDATE Opportunity SET callcount = (obn.count from previous query)
WHERE OpportunityId = OpportunityId

我不确定如何将这两件事加在一起。

由于

1 个答案:

答案 0 :(得分:1)

将第一个查询的结果保存到临时表中,然后使用该表连接更新子句中的另一个表。

SELECT
Opportunity.opportunityid
,obn.cnt as cnt
INTO #CallCounts
FROM Opportunity
LEFT JOIN Account
ON Opportunity.AccountId = Account.AccountId
OUTER APPLY 
(SELECT
    COUNT(dst) AS cnt
FROM [server].[telecoms].[dbo].[vwOpportunityUpdate]
WHERE dst COLLATE DATABASE_DEFAULT = REPLACE(Account.Telephone1,' ','') COLLATE DATABASE_DEFAULT
AND calldate > opportunity.createdon
GROUP BY dst) obn
WHERE DATEDIFF(dd,Opportunity.CreatedOn,GETDATE()) < 30
AND obn.cnt IS NOT NULL

UPDATE o
SET callcount = c.cnt
FROM Opportunity o
JOIN #CallCounts c on c.opportunityID = o.opportunityID

DROP TABLE #CallCounts