将2个单独的sql查询与单独的select语句组合在一起

时间:2013-10-29 07:19:20

标签: sql

我是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

1 个答案:

答案 0 :(得分: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,因为后者可确保每行都不同。