嗨,我几乎不需要帮助来简单地将具有多个distinct行且具有不同值的数据。我需要基于不同的值应用CASE条件,以便提取正确的单个数据集行。
样本核心表'Employee'
ID EmployeeCode DEPT_Code
1 123 X
1 123 X1
1 123 X2
在DEPT_code上,我想应用CASE条件以在一行中产生输出
输出将在单行中。
**ID EmployeeCode Dept_Code**
1 123 __*Case condition value*__
我会这样:
unested
select e.ID, e.EmployeeCode
-- each of C1, C2, C3 DEPT_Code will be null if the condition is not met.
-- nested isnull statements select whichever condition is met first.
,isnull(max(C1.DEPT_Code), isnull(max(C2.DEPT_Code), isnull(max(C3.DEPT_Code), 'unknown'))) DEPT_Code
from Employee e
left outer join ( -- IDs that match your first or second condition, which are the same.
select e1.ID, 'ABC' Dept_Code
from Employee e1
where DEPT_Code = 'X'
group by e1.ID
) C1 on C1.ID = e.ID
left outer join ( -- IDs that match your third condition
select e2.ID, 'xyz' Dept_Code
from Employee e2
group by e2.ID
having min(e2.Dept_Code) = 'X1'
and max(e2.Dept_Code) = 'X1'
) C2 on C2.ID = e.ID
left outer join ( -- IDs that match your fourth condition
select e3.ID, 'opq' Dept_Code
from Employee e3
group by e3.ID
having min(e3.Dept_Code) = 'X2'
and max(e3.Dept_Code) = 'X2'
) C3 on C3.ID = e.ID
group by e.ID, e.EmployeeCode
order by e.ID