0

我是 sql 和 vb 的新手,所以我想知道是否有人可以帮助我这是我现在拥有的表

id total_leadsource total_opportunity
2   1                 3
2   8                 16 

我想结合相同id的total_leadsource和total_opportunity

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
4

1 回答 1

0

你不需要使用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

SELECT DISTINCT另请注意,使用时不需要使用GROUP BY,因为后者可确保每一行都是不同的。

于 2013-10-29T07:29:17.603 回答