按命令分组不对我的查询结果进行分组

时间:2014-02-20 15:41:36

标签: sql sql-server-2012 ssms

Andddd我回来了!我正试图在这个数据库中得到房产销售的数量,我已经得到它来整理城镇的所有销售。完善。我提出了一个分组条款,应该按照他们所在的城镇对它们进行分组,但事实并非如此。我确定这是一个愚蠢的错误,谁能告诉我我错过了什么?

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;

我在想我的错误是在count命令中,但我不确定。

1 个答案:

答案 0 :(得分:2)

您可能希望从town

中删除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;

town中的group by,您正在计算agentid / town组合的匹配数。因此,给定的代理将在多个行上,每个城镇一个。然后,它将给出PaymentList中与该代理关联的行数。

你想做什么?如果您想计算代理商所在的独特城镇,请执行以下操作:

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;