我有两个表员工和 Office , OfficeID 是Employee表中的外键。我需要找到每个办公室的员工人数以及办公室城市和员工名字等其他办公室细节。我写了以下查询:
select o.OfficeID, o.City, o.State, o.Country, o.ZipCode, count(e.EmployeeID)
from Office o
inner join Employee e on o.OfficeID = e.OfficeID
group by o.OfficeID
执行时,我收到以下消息 -
专栏' Office.City'在选择列表中无效,因为它不是 包含在聚合函数或GROUP BY子句中。
如何正确使用group by解决此问题?
感谢
答案 0 :(得分:1)
您需要在select
的{{1}}列表中包含所有非汇总列:
group by
或者,分别汇总select o.OfficeID, o.City, o.State, o.Country, o.ZipCode,
count(e.EmployeeID)
from Office o inner join
Employee e
on o.OfficeID = e.OfficeID
group by o.OfficeID, o.City, o.State, o.Country, o.ZipCode ;
。这是一种方法:
Employee
此表单非常方便,因为您没有外部聚合,并且可以在select o.*, e.cnt
from Office o inner join
(select e.OfficeId, count(*) as cnt
from Employee e
group by e.OfficeId
) e
on o.OfficeID = e.OfficeID;
Office
中包含您喜欢的任何列。
另一种方法使用select
:
cross apply
这有点短。
答案 1 :(得分:0)
select o.OfficeID, o.City, o.State, o.Country, o.ZipCode, e.EmployeeID, e.FirstName, e.LastName , officeCnt.cnt
from Employee e
inner join (select OfficeId, count(*) as cnt from Employee group by OfficeId) as officeCnt
on e.OfficeID = officeCnt.OfficeID;
inner join Office o on e.OfficeID = o.OfficeID
您需要在子查询中计算,您可以通过
来应用分组