如何将GROUP BY子句与COUNT(*)一起使用

时间:2018-01-05 18:14:11

标签: oracle count

我在Oracle数据库上有两个表,一个名为departments_table,另一个名为locations_table。 departments.table有dep_id,dep_name,location_id,staff_id,employer_id。位置表由location_id,city_id,streetname_id和postcode_id组成。如何计算每个位置的部门数量?

以下代码是我试图复制但未成功的代码。下面的错误消息是代码提交后显示的内容。

SELECT dep_name, location_id,
COUNT(*)
FROM departments_table
WHERE location_id => 1
GROUP BY dep_name; 

The results of this is an error, " not a single group function "

2 个答案:

答案 0 :(得分:0)

如果您想要计算每个位置有多少个部门,那么您必须按位置分组,而不是按部门名称分组,对吗?让我们从那开始。

然后,你不需要查询输出中各个部门的任何内容,对吗?您只需要位置ID和部门数量。

select   location_id, count(*) as cnt
from     departments_table
group by location_id
;

这完成了大部分工作。您可能希望在locations_table中添加位于其他地方的位置名称(城市,地址等)。所以你需要一个加入。事实上,该表中可能存在任何部门的位置(他们的ID根本不出现在departments_table中)。如果是这样,您将需要OUTER加入。同样对于那些部门,您可能希望显示0(而不是null) - 您可以使用nvl()函数“修复”该部分。所以你最终会得到像

这样的东西
select l.*, nvl(g.cnt, 0) as department_count
from   locations_table l
       left outer join
       ( select   location_id, count(*) as cnt
         from     departments_table
         group by location_id
       ) g
           on l.location_id = g.location_id
;

答案 1 :(得分:0)

SELECT l.location_id, l.city, COUNT(d.DEPARTMENT_ID)                                                    

FROM OEHR_LOCATIONS l, OEHR_DEPARTMENTS d WHERE l.location_id = d.location_id                           

GROUP BY l.location_id, l.city ORDER BY l.city;

此方法有效。我创建了别名并做了一些小改动。 OEHR代表表名,所以忽略它。

相关问题