Question

Andddd I'm back! I'm trying to get the count of property sales in this db, and I've got it to sort out all the sales by town. Perfect. I put in a group by clause that SHOULD group them by what town they are in, but it is not. I'm sure its a stupid error, can anyone tell me what I'm missing?

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, town;

I'm thinking my error is in the count command, but I'm not sure.

No correct solution

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top