我如何加入这两张桌子?

时间:2012-07-23 08:57:11

标签: sql-server-2008

我有两张桌子。例如,第一个表是父表,即包含deptno(主键)和deptname的部门,另一个表是子表,即包含empid的员工,{{1 },empnamesal(外键)。我想加入这两个表来获得deptno之类的输出以及在该特定部门工作的员工数量。我尝试使用连接,视图,游标,子查询,组子句等查询。我可以使用deptname子句获得一半查询的解决方案,以找出特定部门下的员工数量但是无法弄清楚另一半。

group by

雇员

deptno    deptname
101       sales
102       hr
103       finance

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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

SELECT t1.deptname AS deptname,COUNT(1)AS“员工编号”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>

答案 2 :(得分:0)

请尝试以下代码。

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

希望这能解决您的问题。

答案 3 :(得分: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(*)