diff --git a/最后一舞/存储函数练习题.md b/最后一舞/存储函数练习题.md index d140181..8479fad 100644 --- a/最后一舞/存储函数练习题.md +++ b/最后一舞/存储函数练习题.md @@ -157,17 +157,18 @@ SELECT calculate_years_of_service('2023-12-31'); ```sql DELIMITER $$ DROP FUNCTION IF EXISTS calculate_avg_salary_by_dept; -CREATE FUNCTION calculate_avg_salary_by_dept(deptId INT) +CREATE FUNCTION calculate_avg_salary_by_dept(dept_id INT) RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN RETURN ( - SELECT AVG(salary) + SELECT AVG(e.salary) FROM employee e - WHERE e.dept_id = deptId + WHERE e.dept_id = dept_id ); END $$ DELIMITER ; + SELECT calculate_avg_salary_by_dept(1); ``` @@ -181,7 +182,7 @@ SELECT calculate_avg_salary_by_dept(1); DELIMITER $$ DROP FUNCTION IF EXISTS calculate_avg_salary_by_job; CREATE FUNCTION calculate_avg_salary_by_job(job_id INT) -RETURNS INT +RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN RETURN ( @@ -252,7 +253,7 @@ SELECT is_eligible_for_raise(3000, 1); DELIMITER $$ DROP FUNCTION IF EXISTS calculate_total_salary_by_dept; CREATE FUNCTION calculate_total_salary_by_dept(dept_id INT) -RETURNS INT +RETURNS DECIMAL(10,2) DETERMINISTIC BEGIN RETURN ( @@ -272,6 +273,26 @@ SELECT calculate_total_salary_by_dept(1); 创建一个存储函数 `calculate_total_salary_by_job`,接受职位 ID 作为参数,返回该职位所有员工的总工资。 +```sql +DELIMITER $$ +DROP FUNCTION IF EXISTS calculate_total_salary_by_job; +CREATE FUNCTION calculate_total_salary_by_job(job_id INT) +RETURNS DECIMAL(10,2) +DETERMINISTIC +BEGIN + RETURN ( + SELECT SUM(e.salary) + FROM employee e + WHERE e.job_id = job_id + ); +END $$ +DELIMITER ; + +SELECT calculate_total_salary_by_job(1); +``` + + + #### 练习题 9: 判断员工是否属于高薪部门 创建一个存储函数 `is_high_salary_department`,接受部门 ID 作为参数,返回一个布尔值(1 或 0)。如果该部门的平均工资大于等于 70000,返回 1(高薪部门),否则返回 0(非高薪部门)。