The question:
I am pulling Geo from the Accounts table and I am ranking the Geos by Opportunity $$ Amt based on Accounts that have the name like “Brinks%”.
Accounts are unique, and there can be many opportunities for every account. I need to add the number of employees for each Geo from the accounts table, but since there are many opportunities for each Geo, the number I’m getting is wrong. It seems to be getting multiplied by the number of opportunities it’s tied to. Do I need to change my join? Do I add a subquery? I tried, but I don’t think I’m doing it right. This is what I wrote:
Select
Ac.frm_GEO__c, sum(Op.Amount) Amt
,Rank () Over (Order By sum(Op.Amount) Desc) as 'Rank'
,sum(ac.NumberOfEmployees) num_empl
FROM Account Ac
Inner Join Opportunity Op on Op.AccountId=Ac.Id
Where Ac.Name like 'Brinks%'
Group by Ac.frm_GEO__c
My results are shown below. It’s all correct except the last column.
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
I would solve this with a sub-query. I think that would be the best route available to you. As soon as you JOIN you have expanded the results to be at the granularity of the opportunity. It would be easier to never expand to this granularity and instead retrieve the counts from a subquery:
Select
Ac.frm_GEO__c, [SummarizedOpportunity].Amt
,Rank () Over (Order By [SummarizedOpportunity].Amt Desc) as 'Rank'
,sum(ac.NumberOfEmployees) num_empl
FROM Account Ac
JOIN (SELECT [Opportunity].[AccountId], [Amt] = SUM([Opportunity].[Amount]) FROM [Opportunity] GROUP BY [Opportunity].[AccountId]) [SummarizedOpportunity]
ON [SummarizedOpportunity].[AccountId] = Ac.Id
Where Ac.Name like 'Brinks%'
Group by Ac.frm_GEO__c
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0