Q:

SQL Count certain elements in a group showing each element and total count

Imagine I have a table like this :
+----+--------+--------+------+
| ID |  NAME  | DEPTNO | MGR  |
+----+--------+--------+------+
|  1 | AYEW   |     10 | 4    |
|  2 | JORDAN |     20 | 4    |
|  3 | JAMES  |     20 | 4    |
|  4 | MESSI  |     30 | NULL |
+----+--------+--------+------+

I need to display a result like this :
+----+---------+-------------+--------+-------+
| ID | MANAGER | SUBORDINATE | DEPTNO | COUNT |
+----+---------+-------------+--------+-------+
|  4 | MESSI   | AYEW        |     10 |     1 |
|  4 | MESSI   | JORDAN      |     20 |     2 |
|  4 | MESSI   | JAMES       |     20 |     2 |
+----+---------+-------------+--------+-------+

In other words, I have to count how many subordinates by department got each manager and also show the name and deptno of the subordinates.
I know how to easily associate the managers and subordinates with a JOIN but the problem is in the column of count. How can i count the total subordinates by department showing subordinates names at the same time ? I assume I can't use GROUP BY to count the number of subordinates in each department so I have no idea how to do this. 
Figured out thanks to mathguy's answer it is also possible to do a second join like :
join original_table c on (e.deptno=c.deptno and e.mgr=c.mgr)

so the count column will also show the intended result.

A:

Not sure how the analytic functions are implemented internally - it is possible Gordon's solution is EXACTLY the same as below. (Ordering of rows will probably be different - add an explicit ORDER BY if needed.) NOTE: I took your lead and named a column "count" - in general that is best avoided, as "count" is a reserved word (use "cnt" or something like it instead).
    select m.id, m.name, e.name, e.deptno, c.count 
    from emps e join emps m on e.mgr = m.id
    join (select mgr,deptno, count(*) count from emps where mgr is not null
                             group by mgr, deptno) c
    on e.mgr = c.mgr and e.deptno = c.deptno

    SQL> /
            ID NAME   NAME       DEPTNO      COUNT
    ---------- ------ ------ ---------- ----------
             4 MESSI  JORDAN         20          2
             4 MESSI  JAMES          20          2
             4 MESSI  AYEW           10          1
    3 rows selected.
    Elapsed: 00:00:00.01

