簡體   English   中英

將2個單獨的SQL查詢與單獨的select語句組合

[英]Combining 2 separate sql queries with separate select statement

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

您不需要使用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 ,因為后者可以確保每一行都是不同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM