使用Join计算查询

时间:2014-07-23 10:53:17

标签: mysql

我有桌子

Dept

DEPTNO  DNAME   LOC
10  ACCOUNTING  NEW YORK
20  RESEARCH    DALLAS
30  SALES   CHICAGO
40  OPERATIONS  BOSTON

和另一个表

Emp

EMPNO   ENAME   JOB          MGR    HIREDATE    SAL     COMM    DEPTNO
7369    SMITH   CLERK       7902    12/17/1980  800     NULL     20
7499    ALLEN   SALESMAN    7698    2/20/1981   1600    300      30
7521    WARD    SALESMAN    7698    2/22/1981   1250    500      30
7566    JONES   MANAGER     7839    4/2/1981    2975    NULL     20
7654    MARTIN  SALESMAN    7698    9/28/1981   1250    1400     30
7698    BLAKE   MANAGER     7839    5/1/1981    2850    NULL     30
7782    CLARK   MANAGER     7839    6/9/1981    2450    NULL     10
7788    SCOTT   ANALYST     7566    12/9/1982   3000    NULL     20
7839    KING    PRESIDENT   NULL    11/17/1981  5000    NULL     10
7844    TURNER  SALESMAN    7698    9/8/1981    1500    0        30
7876    ADAMS   CLERK       7788    1/12/1983   1100    NULL     20
7900    JAMES   CLERK       7698    12/3/1981   950     NULL     30
7902    FORD    ANALYST     7566    12/3/1981   3000    NULL     20
7934    MILLER  CLERK       7782    1/23/1982   1300    NULL     10

我的问题:列出所有部门名称及其员工人数。 计数应仅包括雇用日期大于1981年的雇员

结果:应该是这样的

DNAME       EMPCOUNT
ACCOUNTING    1
OPERATIONS    0
RESEARCH      2
SALES         0

请帮助

1 个答案:

答案 0 :(得分:-1)

SELECT DNAME,
       count(emp.deptno) AS EMPCOUNT
FROM DEPT
LEFT JOIN emp ON DEPT.DEPTNO = emp.DEPTNO
WHERE YEAR(hiredate)>1981
GROUP BY emp.deptno