我写了一个查询,将两个表连接起来,得到下面的结果集:
SELECT emp.employee_id,
dept.department_name,
dept.department_id
FROM employee emp,
department dept
WHERE emp.department_id = dept.department_id;
Employee_ID Department Department_ID
Mark Sales D1
Mark Marketing D2
Justin Textiles D3
Kimberley (null) (null)
但是,我需要在输出下面显示一个名为'Status'的新字段。Mark可以在两个部门中工作,因此计数为“ 2”,状态为'Y'(可以显示任何一条记录) )。贾斯汀仅在一个部门工作,计数为1,状态应为“ N”。金伯利在任何地方都不工作,计数为0,状态应为“ N”。
预期输出:
Employee_ID Department Department_ID Status
Mark Sales D1 Y
Justin Textiles D3 N
Kimberley (null) (null) N
请帮助。
我了解您要显示每个用户的第一个部门,并添加一个标志以指示该员工是否至少属于另一个部门。
您可以使用窗口功能:
select
employee_id,
department_name,
department_id
case when cnt <= 1 then 'N' else 'Y' end status
from (
select
emp.employee_id,
dept.department_name,
dept.department_id,
row_number() over(partition by emp.employee_id order by dept.department_id) rn,
count(*) over(partition by emp.employee_id) cnt
from
employee emp
left join department dept on emp.department_id = dept.department_id
) t
where rn = 1
旁注:始终使用显式联接(带有on
关键字),而不是老式的隐式联接(在from
子句中带有逗号),其语法更难于阅读和维护。
您可以做以下类似的事情,只需要一个想法就可以了。如果计数是2或大于1,则只需获取用户计数,然后Status字段为YES,否则为NO。
SELECT CASE Count(emp.employee_id = 2) Then 'Yes'
ELSE 'No'
END Status,
dept.department_name,
dept.department_id
FROM employee emp,
department dept
WHERE emp.department_id = dept.department_id;
在某些情况下,您应该使用关节来联接表,结果会有所不同