我有2个表(employee,Job)
Employee Table
Emp_no Nationality_id Job_Code
1 966 99
2 996 89
3 258 10
4 123 10
5 123 20
6 987 10
工作表
Job_Code Job_Category
99 Finance
89 Finance
10 HR
20 IT
我需要结果:
1-根据job_category中的nationalid_id = 966将所有员工计为Count1
2-根据job_category的国籍ID <> 966将所有员工计数为Count2
想要的结果是这样的
Job_Category Count 1 Count 2
Finance 2 0
HR 0 3
IT 0 1
谢谢
很棒
我还需要将结果1和2加到
餐桌工资
Emp_id Salary
1 1000
2 3000
3 1500
1-根据job_category(国籍ID = 966的工作类别)将所有员工的薪金加起来为sum_1
2-根据job_category的国籍ID <> 966将所有员工的薪水加起来为sum_2
最终结果是
Job_Category Count 1 Count 2 Sum1 Sum 2
Finance 2 0 4000 0
HR 0 3 0 1500
IT 0 1 0 0
答案 0 :(得分:0)
这应该为您做到:
WITH groups as (
Select
CASE WHEN nationality_id = 966 then Count1
Else Count2 END as count_group,
Emp_no
from employees
)
Select
j.Job_Category as Job_Category,
CASE WHEN (g.count_group = Count1) then COUNT(distinct e.Emp_no)
ELSE 0 END as Count1,
CASE WHEN (g.count_group = Count2) then COUNT(distinct e.Emp_no)
ELSE 0 END as Count2
FROM employees as e
LEFT JOIN groups g on e.Emp_no = g.Emp_no
LEFT JOIN Jobs j on e.Job_Code = j.Job_Code
答案 1 :(得分:0)
这是条件聚合。唯一真正的把戏是salary
的外部联接。
select j.job_category,
sum(case when e.nationality = 966 then 1 else 0 end) as cnt_966,
sum(case when e.nationality = 966 then 0 else 1 end) as cnt_other,
sum(case when e.nationality = 966 then s.salary else 0 end) as salary_966,
sum(case when e.nationality = 966 then 0 else s.salary end) as salary_other,
from employees e join
jobs j
on e.job_code = j.job_code left join
salary s
on s.emp_no = e.emp_no
group by j.job_category;