Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 62aec5e

Browse files
authored
Create cte-with-@start.md
1 parent a21a67c commit 62aec5e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎advanced/cte-with-@start.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /