DECLARE @employee TABLE (Eid INT, Ename VARCHAR(50),
L1EmpId INT, L1EmpName VARCHAR(50), L1DepName VARCHAR(50),
L2EmpId INT, L2EmpName VARCHAR(50), L2DepName VARCHAR(50),
L3EmpId INT, L3EmpName VARCHAR(50), L3DepName VARCHAR(50),
L4EmpId INT, L4EmpName VARCHAR(50), L4DepName VARCHAR(50),
L5EmpId INT, L5EmpName VARCHAR(50), L5DepName VARCHAR(50))
INSERT INTO @employee VALUES (101,'AAA', 10001, 'ZZZ', 'Head of IT',1001, 'YYY', 'Vice President',501, 'MMM', 'Project Manager',101, 'AAA','Sales',NULL, NULL,NULL)
INSERT INTO @employee VALUES (102,'BBB', 10001, 'ZZZ', 'Head of IT',1001, 'YYY', 'Vice President',102, 'BBB', 'Service',NULL, NULL,NULL,NULL, NULL,NULL)
INSERT INTO @employee VALUES (103,'CCC', 10001, 'ZZZ', 'Head of IT',1001, 'YYY', 'Vice President',501, 'MMM', 'Project Manager',102, 'BBB', 'Service',103, 'CCC', 'Manamgent')
INSERT INTO @employee VALUES (501,'MMM', 10001, 'ZZZ', 'Head of IT',1001, 'YYY', 'Vice President',501, 'MMM', 'Project Manager',NULL, NULL,NULL,NULL, NULL,NULL)
INSERT INTO @employee VALUES (1001,'YYY', 10001, 'ZZZ', 'Head of IT',NULL, NULL,NULL,NULL, NULL,NULL,NULL, NULL,NULL,NULL, NULL,NULL)
INSERT INTO @employee VALUES (10001,'ZZZ', NULL, NULL,NULL,NULL, NULL,NULL,NULL, NULL,NULL,NULL, NULL,NULL,NULL, NULL,NULL)
; with mycte as
(
select Eid, Ename ,mEid, mEmpName, DepName ,
row_number() over (partition by Eid order by seq desc ) rn
from @employee
cross apply (values
( L1EmpId, L1EmpName, L1DepName,1),
( L2EmpId, L2EmpName, L2DepName,2 ),
( L3EmpId, L3EmpName, L3DepName,3 ),
( L4EmpId, L4EmpName, L4DepName,4 ),
( L5EmpId, L5EmpName, L5DepName,5 )
) t( mEid, mEmpName, DepName ,seq)
where (mEmpName is not null and mEmpName<> Ename)
)
Select Eid, Ename ,mEid, mEmpName, DepName
From mycte
where rn=1
Union all
Select Eid, Ename ,null as mEid, null as mEmpName, null as DepName
from @employee
where L1EmpId is null
/*
Eid Ename mEid mEmpName DepName
101 AAA 501 MMM Project Manager
102 BBB 1001 YYY Vice President
103 CCC 102 BBB Service
501 MMM 1001 YYY Vice President
1001 YYY 10001 ZZZ Head of IT
10001 ZZZ NULL NULL NULL
*/