0

I am using oracle's SQL Developer. To begin with, I have this table:

Name           Null     Type         
-------------- -------- ------------ 
EMPLOYEE_ID    NOT NULL NUMBER(6)    
FIRST_NAME              VARCHAR2(20) 
LAST_NAME      NOT NULL VARCHAR2(25)  
DEPARTMENT_ID           NUMBER(4)  

I would like for each employee to show his name and the number of colleagues from his department. This is what I got so far:

select first_name, department_id, count(employee_id)
from employees
group by department_id;

This generates an error:

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"

I would really need some help. I am a total beginner so any suggestion is welcome.

UPDATE: So, for each Employee, I want to show the number of his colleagues from the same department, and his name. I have updated the question.

4

3 回答 3

3

The query you posted would not generate the error you indicate

SQL> create table employees(
  2    employee_id number primary key,
  3    first_name varchar2(20),
  4    last_name varchar2(25),
  5    department_id number
  6  );

Table created.

SQL> select first_name, department_id, count(employee_id)
  2  from employees
  3  group by first_name, department_id;

no rows selected

However, it would also not produce the results that you seem to indicate that you want. From your description, it appears that you want something like

select first_name, 
       last_name, 
       count(*) over (partition by department_id) - 1 num_colleagues_in_department
  from employees
于 2013-05-30T05:52:58.290 回答
0
select a.firstname, a.department_id, 
(select count(employee_id) from employees b where b.department_id = a.department_id and b.employee_id <> a.employee_id) as total_in_dept
from employees a

this is roughly how I'd do it. It is a subquery. http://www.techonthenet.com/oracle/subqueries.php

于 2013-05-30T05:53:18.273 回答
0

You can do it, among other ways, using a subquery (as many other answers) or a LEFT JOIN like this one;

SELECT u.employee_id, u.first_name, u.last_name, u.department_id,
       COUNT(c.employee_id)-1 colleagues
FROM employees u
LEFT JOIN employees c
  ON u.department_id=c.department_id
GROUP BY u.employee_id, u.first_name, u.last_name, u.department_id
ORDER BY employee_id

A normal JOIN or INNER JOIN would only return users that actually have at least one colleague, a LEFT JOIN returns users even if they don't have a colleague so we can count them.

An SQLfiddle to test with.

于 2013-05-30T06:12:39.100 回答