2

我有两张桌子。例如第一个表是父表,即包含deptno(主键)和deptname的部门,另一个表是子表,即包含empidempname和(外键)sal的员工。deptno我想加入这两个表来获得输出,比如deptname在那个特定部门工作的员工数量。我尝试使用联接、视图、游标、子查询、组子句等进行查询。我可以得到一半查询 usinggroup by子句的解决方案,以找出特定部门下的员工人数,但无法计算出另一半。

deptno    deptname
101       sales
102       hr
103       finance

员工

empid  empname   sal    deptno
  1     john    1500$    101
  2     kevin   1000$    101
  3     james   1200$    101
  4     ford    700$     102
  5     david   855$     102
  6     george  955$     103

我想使用 SQL 查询显示下表。

deptname    no.of employees
sales            3
hr               2
finance          1
4

4 回答 4

1

希望这可以帮助

Select deptname, count(1) no_employees
From table1 t1
Join table2 t2 on t1.deptno = t2.deptno
Group By deptname
Order By Count(1) desc
于 2012-07-23T09:06:29.357 回答
1

SELECT t1.deptname AS deptname, COUNT(1) AS "no. of employees" FROM table1 t1 JOIN table2 t2 ON t2.deptno = t1.deptno GROUP BY t1.deptno;

您可以通过执行以下操作重新创建它:

mysql> 
mysql> CREATE TABLE table1 (deptno INT NOT NULL, deptname VARCHAR(24) NOT NULL, PRIMARY KEY (deptno));
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE table2 (empid INT NOT NULL, empname VARCHAR(48) NOT NULL, sal VARCHAR(16), deptno INT);
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO table1 VALUES (101, "sales"), (102, "hr"), (103, "finance");
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> INSERT INTO table2 VALUES (1, "John", "1500$", 101);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO table2 VALUES (2, "Kevin", "1200$", 101), (3, "James", "1000$", 101);
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> INSERT INTO table2 VALUES (4, "Ford", "700$", 102), (5, "David", "855$", 102), (6, "George", "955$", 103);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT t1.deptname AS deptname, COUNT(1) AS "no. of employees" FROM table1 t1 JOIN table2 t2 ON t2.deptno = t1.deptno GROUP BY t1.deptno;
+----------+------------------+
| deptname | no. of employees |
+----------+------------------+
| sales    |                3 |
| hr       |                2 |
| finance  |                1 |
+----------+------------------+
3 rows in set (0.00 sec)

mysql>
于 2012-07-23T09:09:17.207 回答
0

尝试这个

select d.deptname,COUNT(*) [no.of employees]
from employee E join department D
on E.deptno=D.deptno
group by d.deptname
order by COUNT(*)
于 2012-07-23T09:06:44.890 回答
0

试试下面的代码。

select COUNT(*) from tblEmp E inner join tblDept d on d.Deptid=l.Deptid

希望这能解决您的问题。

于 2012-07-23T09:01:48.227 回答