You probably want to remove town
from the group by
:
SELECT rl.AgentID, rl.first_name, rl.last_name, Count(town) as Town
FROM [INTERN_DB2].[dbo].[PaymentList] pl inner join
(Select agentID, min(first_name) as first_name, min(last_name) as last_name
From [Intern_DB2]..[RealEstateAgentList]
GROUP BY agentID, first_name, last_name
) rl
ON rl.AgentID = pl.AgentID
GROUP BY rl.AgentID, rl.first_name, rl.last_name;
With town
in the group by
, you are counting the number of matches for an agentid
/town
combination. So a given agent will be on multiple rows, one for each town. It will then give the number of rows in PaymentList
that are associated with that agent.
What do you want to do? If you want to count the unique towns where an agent is, then do this:
SELECT rl.AgentID, rl.first_name, rl.last_name, Count(distinct town) as Town
FROM [INTERN_DB2].[dbo].[PaymentList] pl inner join
(Select agentID, min(first_name) as first_name, min(last_name) as last_name
From [Intern_DB2]..[RealEstateAgentList]
GROUP BY agentID, first_name, last_name
) rl
ON rl.AgentID = pl.AgentID
GROUP BY rl.AgentID, rl.first_name, rl.last_name;