Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 8 - SQL Query to find department with highest number of employees

Suggested Videos:
Part 5 - SQL query to find employees hired in last n months
Part 6 - Transform rows into columns in sql server
Part 7 - SQL query to find rows that contain only numerical data

We will be using the following tables (Employees & Departments) to answer this question. In Employees table DepartmentID is the foreign key referencing DepartmentID column in Departments table.
SQL Query to retrieve department name with maximum employees

SQL Script to create the required tables
Create Table Departments
     DepartmentID int primary key,
     DepartmentName nvarchar(50)

Create Table Employees
     EmployeeID int primary key,
     EmployeeName nvarchar(50),
     DepartmentID int foreign key references Departments(DepartmentID)

Insert into Departments values (1, 'IT')
Insert into Departments values (2, 'HR')
Insert into Departments values (3, 'Payroll')

Insert into Employees values (1, 'Mark', 1)
Insert into Employees values (2, 'John', 1)
Insert into Employees values (3, 'Mike', 1)
Insert into Employees values (4, 'Mary', 2)
Insert into Employees values (5, 'Stacy', 3)

Scenario asked in the SQL Server Interview
Based on the above two tables write a SQL Query to get the name of the Department that has got the maximum number of Employees. To answer this question it will be helpful if you the knowledge of JOINS & GROUP BY in SQL Server. We discusses these in Parts 11 & 12 of SQL Server Tutorial video series

SQL query that retrieves the department name with maximum number of employees
SELECT TOP 1 DepartmentName
FROM Employees
JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
GROUP BY DepartmentName

sql server interview questions and answers

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.