我可以根据条件将值插入列吗? SQL Server

时间:2014-09-05 15:57:42

标签: sql sql-server insert

我想知道我怎么能,例如,如果我有:

Employees:  nameOfEmployee,numberOfEmployee,numberOfDepartment,....,....,....,....,...,....,....
Departments:  numberOfDepartment,numberOfEmployees,....,....,....,....,...,....,....

并且表中已有行,通过添加nameOfEmployee来填充Departments.numberOfEmployees中的值

到目前为止,我唯一想到的就是:

UPDATE Departments
SET numberOfEmployees=COUNT(Employees.nameOfEmployee)
FROM Employees
WHERE Departments.numberOfDepartment=Employees.numberOfDepartment

我知道这可能甚至没有任何意义。我刚刚开始使用SQL

1 个答案:

答案 0 :(得分:2)

试试这个(UNTESTED)

UPDATE Departments
SET numberOfEmployees=(SELECT COUNT(Employees.nameOfEmployee)
FROM Employees
WHERE Departments.numberOfDepartment=Employees.numberOfDepartment)