A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

8.2 Window Functions

 In SQL Server, Window Functions are powerful tools for performing calculations across a specified range of rows related to the current row within the result set. They are used with the OVER clause and can be applied to aggregate functions and ranking functions. Let's explore some common window functions.

8.2.1 ROW_NUMBER()

The ROW_NUMBER() function assigns a unique integer to each row within a partition of the result set.

SELECT
    ProductID,
    ProductName,
    CategoryID,
    ROW_NUMBER() OVER (ORDER BY ProductID) AS RowNum
FROM
    Products;

ProductIDProductNameCategoryIDRowNum
1Product A11
2Product B12
3Product C23
............

8.2.2 RANK() and DENSE_RANK()

The RANK() and DENSE_RANK() functions assign a ranking to each row based on the specified column order.

SELECT
    EmployeeID,
    FirstName,
    LastName,
    Salary,
    RANK() OVER (ORDER BY Salary DESC) AS Rank,
    DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank
FROM
    Employees;

EmployeeIDFirstNameLastNameSalaryRankDenseRank
1JohnDoe6000011
2JaneSmith5500022
3BobJohnson5500022
..................

8.2.3 LAG() and LEAD()

The LAG() and LEAD() functions allow you to access data from previous and subsequent rows in the result set.

SELECT
    OrderID,
    OrderDate,
    TotalAmount,
    LAG(TotalAmount) OVER (ORDER BY OrderDate) AS PrevAmount,
    LEAD(TotalAmount) OVER (ORDER BY OrderDate) AS NextAmount
FROM
    Orders;

OrderIDOrderDateTotalAmountPrevAmountNextAmount
12023-01-01 08:00:00100.00NULL150.00
22023-01-02 10:30:00150.00100.00120.00
32023-01-03 12:45:00120.00150.00NULL
...............

8.2.4 SUM() Over a Partition

The SUM() function can be used over a specific partition of the result set.

SELECT
    CategoryID,
    ProductName,
    Price,
    SUM(Price) OVER (PARTITION BY CategoryID) AS CategoryTotal
FROM
    Products;

CategoryIDProductNamePriceCategoryTotal
1Product A50.00150.00
1Product B70.00150.00
2Product C80.0080.00
............

These examples showcase the versatility of window functions in SQL Server. Experiment with these functions to gain a deeper understanding of their capabilities.