如上所述,这非常混乱,因为您需要使用 CASE 语句来确定虚拟employee_id
. 如果您可以将此 CASE 语句重构为 udf,或者将结果存储在表中,那会简单得多!
为了澄清这将要做什么 - 您希望将表连接到employee
包含每个员工计数的表上。计数表如下所示:
SELECT employee_id, COUNT(*) AS employee_count
FROM employee
GROUP BY employee_id
将它们连接在一起看起来像这样:
SELECT ...
FROM employee
JOIN (SELECT employee_id, COUNT(*) AS employee_count
FROM employee
GROUP BY employee_id) ec
ON employee.employee_id = ec.employee_id
您计算的薪水现在将变为:
CASE
WHEN ec.employee_count > 1
THEN CAST((total_salary)AS NUMERIC (18,2))* CAST((assign_perc) AS NUMERIC (18,2))
ELSE total_salary
END AS salary,
下面是用怪异的 CASE 语句代替“employee_id”的完整查询:
SELECT
CASE employee.employee_id
WHEN ''
THEN RTRIM(last_name) + '_' + RTRIM(first_name)
+ '_' + RTRIM(gender) + '_'
+ RTRIM(race_ethnicity_code) + '_'
+ RTRIM(high_degree_code) + '_' + RTRIM(position_code) + '_'
+ RTRIM(assignment_code)
ELSE employee.employee_id
END AS emp_id,
last_name, first_name,
assign_perc,
assignment_num,
CASE
WHEN ec.employee_count > 1
THEN CAST((total_salary)AS NUMERIC (18,2))* CAST((assign_perc) AS NUMERIC (18,2))
ELSE total_salary
END AS salary,
total_salary
FROM employee
JOIN (SELECT CASE employee.employee_id
WHEN ''
THEN RTRIM(last_name) + '_' + RTRIM(first_name)
+ '_' + RTRIM(gender) + '_'
+ RTRIM(race_ethnicity_code) + '_'
+ RTRIM(high_degree_code) + '_' + RTRIM(position_code) + '_'
+ RTRIM(assignment_code)
ELSE employee.employee_id
END AS employee_id, COUNT(*) employee_count
FROM employee
GROUP BY CASE employee.employee_id
WHEN ''
THEN RTRIM(last_name) + '_' + RTRIM(first_name)
+ '_' + RTRIM(gender) + '_'
+ RTRIM(race_ethnicity_code) + '_'
+ RTRIM(high_degree_code) + '_' + RTRIM(position_code) + '_'
+ RTRIM(assignment_code)
ELSE employee.employee_id
END) ec
ON CASE employee.employee_id
WHEN ''
THEN RTRIM(last_name) + '_' + RTRIM(first_name)
+ '_' + RTRIM(gender) + '_'
+ RTRIM(race_ethnicity_code) + '_'
+ RTRIM(high_degree_code) + '_' + RTRIM(position_code) + '_'
+ RTRIM(assignment_code)
ELSE employee.employee_id
END = ec.employee_id
ORDER BY last_name, first_name, district_name