结合这些SQL查询

时间:2016-01-18 17:16:09

标签: sql sql-server

我有这两个问题:

--query 1
SELECT Account.*, Opportunity.* FROM Opportunity
LEFT JOIN Account
ON Opportunity.AccountId = Account.AccountId
WHERE YEAR(Opportunity.CreatedOn) = 2016

--query 2
SELECT outbound_number, count(outbound_number) as c
FROM [Telecoms].[dbo].[cdr]
WHERE YEAR(calldate) = 2016 and calltype = 'outgoing' AND Disposition = 'ANSWERED'
GROUP BY outbound_number

我试图将它们组合起来,因此对于第一行中的每一行,我也可以看到第二行WHERE Account.Telephone1 = outbound_number中的计数。

使这项工作正确的语法是什么?

4 个答案:

答案 0 :(得分:1)

只需执行以下子查询:

SELECT Opportunity.*, Account.*, TotalOutboundCalls=OBN.c
   FROM Opportunity
      LEFT OUTER JOIN Account ON Opportunity.AccountId = Account.AccountId
      LEFT OUTER JOIN (
         SELECT outbound_number, c=count(outbound_number)
             FROM [Telecoms].[dbo].[cdr]
             WHERE YEAR(calldate) = 2016 
                AND calltype = 'outgoing' 
                AND Disposition = 'ANSWERED'
             GROUP BY outbound_number
       ) OBN ON Account.Telephone1 = OBN.outbound_number
  WHERE YEAR(Opportunity.CreatedOn) = 2016

答案 1 :(得分:1)

试试这个 -

SELECT
    Account.*
    ,Opportunity.*
    ,obn.cnt
FROM Opportunity
LEFT JOIN Account
    ON Opportunity.AccountId = Account.AccountId
OUTER APPLY 
    (SELECT
        COUNT(outbound_number) AS cnt
    FROM [Telecoms].[dbo].[cdr]
    WHERE YEAR(calldate) = 2016
    AND calltype = 'outgoing'
    AND Disposition = 'ANSWERED'
    AND outbound_number = Account.Telephone1
    GROUP BY outbound_number) obn
WHERE YEAR(Opportunity.CreatedOn) = 2016

答案 2 :(得分:0)

我相信这可以在单个查询中完成

试试这个

SELECT account.*, 
       opportunity.*, 
       Count(outbound_number) OVER(partition BY outbound_number) AS outbound_count 
FROM   opportunity 
       LEFT JOIN account 
              ON opportunity.accountid = account.accountid 
       LEFT JOIN [Telecoms].[dbo].[cdr] C
              ON Account.Telephone1 = C.outbound_number
             AND C.calltype = 'outgoing' 
             AND C.disposition = 'ANSWERED'
WHERE  Year(opportunity.createdon) = 2016 

答案 3 :(得分:0)

我认为你需要这样的东西:

while(<>){}

你需要把东西放进去?您无法使用SELECT Account.??, Opportunity.??, count(TDC.outbound_number) FROM Opportunity LEFT JOIN Account ON Opportunity.AccountId = Account.AccountId LEFT JOIN [Telecoms].[dbo].[cdr] TDC ON TDC.outbound_number = Account.Telephone1 AND YEAR(TDC.calldate) = 2016 AND TDC.calltype = 'outgoing' AND TDC.Disposition = 'ANSWERED' WHERE YEAR(Opportunity.CreatedOn) = 2016 GROUP BY ??, ?? 语法进行分组。您需要明确地调出要分组的字段。