2013-10-29 115 views
0

我是新来的SQL和VB,所以我想知道是否有人能帮助我,这是表,我现在有结合2个独立的SQL查询与独立select语句

id total_leadsource total_opportunity 
2 1     3 
2 8     16 

,我想结合相同的ID

SELECT distinct id,LeadSource,SUM (WeightedAmount) as Weighted_Amount, 
     COUNT(distinct oppLeadSourceID) + COUNT (distinct case when oppLeadSourceID is null then 0 end) as Total_LeadSource, 
     count(OppLeadSourceID) as Total_Opportunity 
FROM leadS A 
LEFT JOIN opportunity B on B.Source = A.id 
WHERE (OwnerCode =1486 
     OR AOCode =1486 
     OR PM = 1486) 
GROUP BY id,LeadSource 
UNION 
SELECT distinct id,LeadSource,SUM (WeightedAmount) as Weighted_Amount, 
     COUNT(distinct oppLeadSourceID) + COUNT (distinct case when oppLeadSourceID is null then 0 end) as Total_LeadSource, 
     count(OppLeadSourceID) as Total_Opportunity 
FROM leadS A 
LEFT JOIN opportunity B on B.Source = A.id 
WHERE (OwnerCode =55856 
     OR AOCode =55856 
     OR PM = 55856) 
GROUP BY id,LeadSource 

回答

0

的total_leadsource和total_opportunity使用UNION你不需要。只要使用符合两个条件的WHERE子句。

SELECT id,LeadSource,SUM (WeightedAmount) as Weighted_Amount, 
     COUNT(distinct oppLeadSourceID) + COUNT(distinct case when oppLeadSourceID is null then 0 end) as Total_LeadSource, 
     COUNT(OppLeadSourceID) as Total_Opportunity 
FROM leadS A 
LEFT JOIN opportunity B on B.Source = A.id 
WHERE (OwnerCode IN (1486, 55856) 
     OR AOCode IN (1486, 55856) 
     OR PM IN (1486, 55856)) 
GROUP BY id,LeadSource 

并且,用GROUP BY当你不需要使用SELECT DISTINCT,因为后者可以确保每一行都会是不同的。

+0

哇,完美谢谢= D –