Advanced SQL Analysis with Window Functions, Subqueries, and CTEs
This report showcases advanced SQL Server techniques including Window Functions, Subqueries, and
Common Table Expressions (CTEs). The examples analyze employee performance, salary trends, and
department-level insights.
1. Create Sample Tables
CREATE TABLE Employees (
EmpID INT,
Name VARCHAR(50),
DeptID INT,
Salary INT,
JoinDate DATE
);
CREATE TABLE Departments (
DeptID INT,
DeptName VARCHAR(50)
);
2. Insert Sample Data
INSERT INTO Employees VALUES (1, 'Alice', 1, 60000, '2021-01-15');
INSERT INTO Employees VALUES (2, 'Bob', 1, 55000, '2022-03-22');
INSERT INTO Employees VALUES (3, 'Charlie', 2, 70000, '2021-05-10');
INSERT INTO Employees VALUES (4, 'David', 2, 72000, '2023-02-01');
INSERT INTO Employees VALUES (5, 'Eva', 3, 50000, '2021-08-12');
INSERT INTO Departments VALUES (1, 'HR');
INSERT INTO Departments VALUES (2, 'Finance');
INSERT INTO Departments VALUES (3, 'IT');
3. Use of Window Function - RANK Employees by Salary
SELECT Name, DeptID, Salary,
RANK() OVER(PARTITION BY DeptID ORDER BY Salary DESC) AS SalaryRank
FROM Employees;
-- Shows ranking of employees within each department based on salary
4. Use of Subquery - Find Employees Earning Above Department Average
SELECT Name, Salary, DeptID
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees AS E2
WHERE E2.DeptID = Employees.DeptID
);
-- Lists employees whose salary is above their department's average
5. Use of CTE - Find Recent Joiners
WITH RecentJoiners AS (
SELECT Name, JoinDate
FROM Employees
WHERE JoinDate >= '2022-01-01'
SELECT * FROM RecentJoiners;
-- Returns employees who joined in 2022 or later
6. Combine All: Department with Highest Average Salary
WITH DeptAvg AS (
SELECT DeptID, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY DeptID
SELECT d.DeptName, da.AvgSalary
FROM DeptAvg da
JOIN Departments d ON da.DeptID = d.DeptID
WHERE da.AvgSalary = (SELECT MAX(AvgSalary) FROM DeptAvg);
-- Returns the department(s) with the highest average salary