Introduction
This is an interview question. It seems very simple, but there are some tricks to it. Analyzing it can review some important concepts of SQL Query.
Question
Given a table with four columns,
- Employees - table with columns,
- Id
- Name
- Salary
- ManagerId
Request
Get the Manager's Name, the employee amount per manager, and the total salaries for each team.
A. Set up Table and initial Data
Set up the Table by the question,
USE [TestDB]
GO
/****** Object: Table [dbo].[Employees] Script Date: 5/28/2021 7:42:51 PM ******/ SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo]
.
[Employees](
[Id] [int] IDENTITY(1, 1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Salary] [int] NOT NULL,
[ManagerId] [int] NOT NULL,
CONSTRAINT [PK_dbo.Employees] PRIMARY KEY CLUSTERED (
[Id] ASC )WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON
[PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Insert initial Data
insert dbo.Employees
Values ('Greg', 100000, 1),
('George', 150000, 1),
('Helen', 130000, 1),
('Tom', 120000, 2),
('Kevin', 110000, 2),
('David', 120000, 3),
('Geek', 110000,3),
('Tesla', 120000,3)
The result will be,

B. Self JOIN in SQL
This is a self-JOIN issue. A self-join is a regular join, but the table is joined with itself. We review the JOIN types below; find a detailed article about Joins in SQL here: Joins in SQL
Different Types of SQL JOINs
Here are the different types of JOINs in SQL,
- (INNER)JOIN. Returns records that have matching values in both tables
- LEFT(OUTER)JOIN. Returns all records from the left table and the matched records from the right table
- RIGHT(OUTER)JOIN. Returns all records from the right table, and the matched records from the left table
- FULL(OUTER)JOIN. Returns all records when there is a match in the either the left or right table

We make a self-JOIN,





Join the conversation! Your thoughts help the community grow.