我正在运行一个查询,该查询在查询中搜索特定列的不为空的实例,然后按月将其分解。这工作正常,但我还需要添加一个子查询,该子查询连接另一个表并查找其中的另一个列的实例。这是查询:
SELECT
DATEPART(MONTH, CreatedDate) AS TheMonth,
COUNT(CreatedDate) AS NASCL,
COUNT(SQL_Date) AS NASQL,
COUNT(Demo_Completed_Date) AS NADEMO,
COUNT(Converted_Date) AS NAOPP,
(SELECT
COUNT(lead_load.Converted_OpportunityId)
FROM lead_load
INNER JOIN Opportunity_load
ON lead_load.Converted_OpportunityId = Opportunity_load.Id
WHERE Opportunity_load.Stage_Name = 'Closed Won') AS NACONV
FROM lead_load
WHERE Region='North America'
AND LeadSource NOT IN ('Advertising', 'Trade Show', 'Social', 'Partner', 'Organic Search', 'Paid Search', 'Direct', 'Referral')
AND CreatedDate > '2014-07-16'
GROUP BY
DATEPART(MONTH, CreatedDate);
问题是,如果我尝试将DATEPART
放入子查询中,则会出错,因为我没有对其进行分组或通过它进行聚合,结果只汇总了Opportuunity_load.Id
的所有实例{}始终{1}}。
我如何进行下一步并逐月解决这个问题,因为我有其他人?
提前致谢。
答案 0 :(得分:0)
尝试此操作,将子查询移动到另一个嵌套查询中:
SELECT *
,(SELECT
COUNT(lead_load.Converted_OpportunityId)
FROM lead_load
INNER JOIN Opportunity_load
ON lead_load.Converted_OpportunityId = Opportunity_load.Id
WHERE Opportunity_load.Stage_Name = 'Closed Won') AS NACONV
FROM (
SELECT
DATEPART(MONTH, CreatedDate) AS TheMonth,
COUNT(CreatedDate) AS NASCL,
COUNT(SQL_Date) AS NASQL,
COUNT(Demo_Completed_Date) AS NADEMO,
COUNT(Converted_Date) AS NAOPP,
FROM lead_load
WHERE Region='North America'
AND LeadSource NOT IN ('Advertising', 'Trade Show', 'Social', 'Partner', 'Organic Search', 'Paid Search', 'Direct', 'Referral')
AND CreatedDate > '2014-07-16'
GROUP BY DATEPART(MONTH, CreatedDate)
) tmp;