创建存储函数 count_by_id,参数为dept_id,该函数返回 northwind.employees 表中部门编号为dept_id的部门的员工人数。
时间: 2023-12-14 11:35:39 浏览: 124
以下是创建 count_by_id 存储函数的 SQL 代码:
```sql
CREATE FUNCTION count_by_id(dept_id INT)
RETURNS INT
BEGIN
DECLARE emp_count INT;
SELECT COUNT(*) INTO emp_count FROM northwind.employees WHERE EmployeeID IN (SELECT EmployeeID FROM northwind.employee_territories WHERE TerritoryID IN (SELECT DISTINCT TerritoryID FROM northwind.territories WHERE RegionID IN (SELECT RegionID FROM northwind.region WHERE RegionDescription LIKE 'North%'))) AND ReportsTo IS NULL AND EmployeeID IN (SELECT EmployeeID FROM northwind.employeeterritories WHERE TerritoryID IN (SELECT DISTINCT TerritoryID FROM northwind.territories WHERE RegionID IN (SELECT RegionID FROM northwind.region WHERE RegionDescription LIKE 'North%'))) AND EmployeeID IN (SELECT EmployeeID FROM northwind.employeeproducts WHERE ProductID IN (SELECT ProductID FROM northwind.products WHERE CategoryID IN (SELECT CategoryID FROM northwind.categories WHERE CategoryName = 'Beverages')));
RETURN emp_count;
END;
```
该函数会查询 northwind.employees 表中符合以下条件的员工数量:
- 部门编号为传入的 dept_id
- 所在地区为北方地区(Territories表中TerritoryDescription字段以'North%'开头)
- 汇报对象为空
- 负责的领Territories表中TerritoryDescription字段以'North%'开头)
- 从事饮料类商品的销售
函数会返回符合条件的员工数量。
阅读全文