|
| 1 | +This SQL function GetRankedSalesByEmployee takes two parameters: @startDate and @endDate, which define the date range for the sales records to be considered. It returns a table that includes the `EmployeeID`, `FirstName`, `LastName`, total sales amount as TotalAmount, and the sales rank of each employee. |
| 2 | + |
| 3 | +The function uses two Common Table Expressions (`CTEs`): |
| 4 | + |
| 5 | +`TotalSales`: Calculates the total sales amount for each employee within the given date range. |
| 6 | +`RankedSales`: Joins the TotalSales CTE with the Employees table to get employee details and ranks them based on the total sales amount. |
| 7 | +Finally, the function returns the ranked list of employees and their total sales amount. This function can be called in a SELECT statement to retrieve the desired data. |
| 8 | + |
| 9 | +```sql |
| 10 | +CREATE FUNCTION GetRankedSalesByEmployee(@startDate DATE, @endDate DATE) |
| 11 | +RETURNS TABLE |
| 12 | +AS |
| 13 | +RETURN ( |
| 14 | + WITH TotalSales AS ( |
| 15 | + SELECT |
| 16 | + EmployeeID, |
| 17 | + SUM(Amount) AS TotalAmount |
| 18 | + FROM |
| 19 | + Sales |
| 20 | + WHERE |
| 21 | + SaleDate BETWEEN @startDate AND @endDate |
| 22 | + GROUP BY |
| 23 | + EmployeeID |
| 24 | + ), |
| 25 | + RankedSales AS ( |
| 26 | + SELECT |
| 27 | + E.EmployeeID, |
| 28 | + E.FirstName, |
| 29 | + E.LastName, |
| 30 | + T.TotalAmount, |
| 31 | + RANK() OVER (ORDER BY T.TotalAmount DESC) AS Rank |
| 32 | + FROM |
| 33 | + Employees E |
| 34 | + INNER JOIN |
| 35 | + TotalSales T ON E.EmployeeID = T.EmployeeID |
| 36 | + ) |
| 37 | + SELECT |
| 38 | + EmployeeID, |
| 39 | + FirstName, |
| 40 | + LastName, |
| 41 | + TotalAmount, |
| 42 | + Rank |
| 43 | + FROM |
| 44 | + RankedSales |
| 45 | +) |
| 46 | +``` |
0 commit comments