帮我写一个5张表关联,十个函数的sql
时间: 2024-11-29 15:38:53 浏览: 11
在编写一个涉及多个表关联和多种函数的SQL查询时,首先要明确业务需求,这里假设我们需要计算各部门员工的平均工资,包括每个员工的奖金收入,并考虑年龄和工作年限的影响。假设我们有五个表:`employees`,`departments`,`salaries`,`bonuses` 和 `years_of_experience`。以下是示例查询:
```sql
WITH
-- 引入部门ID和员工ID之间的关系
department_employees AS (
SELECT e.employee_id, d.department_id
FROM employees e
JOIN departments d ON e.department_id = d.department_id
),
-- 计算员工工资加奖金总和
total_income AS (
SELECT
e.employee_id,
d.department_id,
(s.salary + b.bonus) AS total_income
FROM department_employees e
LEFT JOIN salaries s ON e.employee_id = s.employee_id
LEFT JOIN bonuses b ON e.employee_id = b.employee_id
),
-- 添加工作经验影响
experience_weighted_income AS (
SELECT
t.*,
CASE
WHEN years_of_experience <= 5 THEN (total_income * 0.9)
WHEN years_of_experience > 5 AND years_of_experience <= 10 THEN (total_income * 0.95)
ELSE (total_income)
END AS weighted_total_income
FROM total_income t
LEFT JOIN years_of_experience ye ON e.employee_id = ye.employee_id
)
-- 计算平均值
SELECT
d.department_name,
AVG(weighted_total_income) AS avg_salary_with_bonus
FROM experience_weighted_income ewi
GROUP BY d.department_name
ORDER BY avg_salary_with_bonus DESC;
```
这个查询做了以下几件事:
1. 使用`WITH`语句创建了两个临时表:`department_employees`和`experience_weighted_income`
2. 汇总员工的工资和奖金作为总收入
3. 根据工作年限调整总收入
4. 计算每个部门的平均工资
阅读全文