Hernan Demczuk
Hernan Demczuk

Reputation: 405

Can I insert values to a column according to a condition? SQL Server

I was wondering how can I , for example, if I have:

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

and there is already rows in the tables, fill the values in Departments.numberOfEmployees with the adding of nameOfEmployee

The only thing I came up with so far is this:

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

I know this probably won't even make any sence. I'm just getting started with SQL

Upvotes: 1

Views: 152

Answers (1)

Youness
Youness

Reputation: 1495

just try this (UNTESTED)

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

Upvotes: 2

Related Questions