Master SQL Server From Scratch

Clear, interactive, and structured SQL Server lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to SQL Server
Introduction to SQL Server SQL Server Installation SQL Server Fundamentals
2. Data Types
Data Types Numeric Data Types Character & String Data Types Date & Time Data Types Other SQL Server Data Types
3. Database & Tables
Database & Tables Introduction Creating a Database Creating Tables Table Structure Altering Tables Dropping Tables
4. Constraints
Constraints Introduction PRIMARY KEY FOREIGN KEY UNIQUE Constraint NOT NULL & DEFAULT CHECK Constraint
5. SQL Basics
SQL Basics Introduction SQL Commands SQL Command Categories SELECT Statement INSERT, UPDATE & DELETE
6. CRUD Operations
CRUD Operations Introduction INSERT Operation SELECT Operation UPDATE Operation DELETE Operation
7. SQL Queries
Queries Introduction WHERE Clause ORDER BY Clause DISTINCT LIKE Operator IN, BETWEEN & IS NULL
8. Joins
Joins Introduction INNER JOIN LEFT JOIN RIGHT JOIN FULL OUTER JOIN CROSS JOIN
9. SQL Functions
SQL Functions Introduction String Functions Numeric Functions Date & Time Functions Conversion Functions NULL Functions
10. Grouping & Aggregate Functions
GROUP BY Aggregate Functions COUNT() SUM() AVG() MIN() & MAX()
11. Subqueries
Subqueries Introduction Single-Row Subquery Multiple-Row Subquery Correlated Subquery Subquery with DML
12. Views
SQL Views Introduction Creating a View Updating a View Altering a View Dropping a View
13. Stored Procedures
Stored Procedures Introduction Creating a Stored Procedure Input Parameters Output Parameters Executing & Modifying Stored Procedures
14. Triggers
Triggers Introduction AFTER INSERT Trigger AFTER UPDATE Trigger AFTER DELETE Trigger INSTEAD OF Trigger
15. Transactions
Transactions Introduction COMMIT ROLLBACK SAVEPOINT Transaction with TRY...CATCH
16. Indexes
Indexes Introduction Clustered Index Non-Clustered Index Creating & Dropping Indexes Index Performance
17. Common Table Expressions
CTE Introduction Simple CTE CTE with JOIN CTE with Aggregate Functions Recursive CTE
18. Window Functions
Window Functions Introduction ROW_NUMBER() RANK() and DENSE_RANK() LEAD() and LAG() PARTITION BY
19. Advanced SQL
Advanced SQL Introduction Temporary Tables Table Variables Dynamic SQL Error Handling Performance Optimization

CTE with Aggregate Functions

Learn how to use aggregate functions such as COUNT, SUM, AVG, MIN and MAX with Common Table Expressions in SQL Server.

What are Aggregate Functions?

Aggregate functions perform calculations on a set of rows and return a single result or a result for each group.

Common aggregate functions in SQL Server include:

  • COUNT() - Counts the number of rows.
  • SUM() - Calculates the total value.
  • AVG() - Calculates the average value.
  • MIN() - Returns the minimum value.
  • MAX() - Returns the maximum value.

Example Employees Table

EmployeeId | EmployeeName | Department | Salary
--------------------------------------------------
101        | Amit          | IT         | 60000
102        | Rahul         | HR         | 45000
103        | Priya         | IT         | 70000
104        | Sneha         | Finance    | 55000
105        | Raj           | IT         | 65000

CTE with AVG()

The following CTE calculates the average salary of employees in each department.

WITH DepartmentSalary AS
(
    SELECT
        Department,
        AVG(Salary) AS AverageSalary
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentSalary;

Result

Department Average Salary
IT 65000
HR 45000
Finance 55000

CTE with COUNT()

We can use COUNT() to find the number of employees in each department.

WITH DepartmentEmployeeCount AS
(
    SELECT
        Department,
        COUNT(*) AS EmployeeCount
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentEmployeeCount;

CTE with SUM()

SUM() can be used to calculate the total salary for each department.

WITH DepartmentTotalSalary AS
(
    SELECT
        Department,
        SUM(Salary) AS TotalSalary
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentTotalSalary;

CTE with MIN() and MAX()

MIN() and MAX() can be used to find the lowest and highest salary in each department.

WITH DepartmentSalaryRange AS
(
    SELECT
        Department,
        MIN(Salary) AS MinimumSalary,
        MAX(Salary) AS MaximumSalary
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentSalaryRange;

Multiple Aggregate Functions

Multiple aggregate functions can be used inside the same CTE.

WITH DepartmentStatistics AS
(
    SELECT
        Department,
        COUNT(*) AS EmployeeCount,
        SUM(Salary) AS TotalSalary,
        AVG(Salary) AS AverageSalary,
        MIN(Salary) AS MinimumSalary,
        MAX(Salary) AS MaximumSalary
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentStatistics;

Filtering Aggregate Results

Once the aggregate result is generated by the CTE, the main query can filter that result.

WITH DepartmentStatistics AS
(
    SELECT
        Department,
        COUNT(*) AS EmployeeCount,
        AVG(Salary) AS AverageSalary
    FROM Employees
    GROUP BY Department
)
SELECT *
FROM DepartmentStatistics
WHERE AverageSalary > 50000;

CTE with HAVING

The HAVING clause can be used inside the CTE when we want to filter grouped results.

WITH DepartmentStatistics AS
(
    SELECT
        Department,
        AVG(Salary) AS AverageSalary
    FROM Employees
    GROUP BY Department
    HAVING AVG(Salary) > 50000
)
SELECT *
FROM DepartmentStatistics;

How CTE with Aggregate Functions Works

  1. The CTE starts with the WITH keyword.
  2. The required rows are selected from the table.
  3. GROUP BY groups the records when required.
  4. Aggregate functions perform calculations on the groups.
  5. The main query reads the result produced by the CTE.

Advantages

  • Makes aggregate queries easier to understand.
  • Separates aggregation logic from the final query.
  • Makes complex grouped queries more readable.
  • Allows the aggregate result to be filtered in the main query.
  • Helps organize reporting queries.

Important Points

  • Aggregate functions can be used inside a CTE.
  • GROUP BY is commonly used with aggregate functions.
  • HAVING can filter grouped results.
  • The main query can further filter or sort the CTE result.
  • Multiple aggregate functions can be used in the same CTE.

Summary

CTEs can be combined with aggregate functions to perform calculations such as COUNT, SUM, AVG, MIN and MAX.

Using a CTE keeps the aggregation logic organized and makes complex reporting queries easier to read and maintain.