我有两个包含以下架构的表:
A)
--------------
Employee
--------------
EmpID EmpName
1 Abc
B)
Address
-----------------------------------
AddressId EmpID Address1 Status
-----------------------------------
1 1 Abc 1 Active
2 1 Abc 2 Inactive
我希望根据以下情况显示员工详细信息,例如EmpName,Address1:
以下是我的Sql查询
SELECT a.EmpID, a.status, Count(a.Status) as Count,
CASE
WHEN Count(a.Status) = 1 and a.Status In ('Active', 'Inactive')
THEN (select top 1 a.Address1 from Address a where a.Status = 'Active')
WHEN a.Status= 'Inactive' and count(a.Status) = 1
THEN (select top 1 a.Address1 from Address a where a.Status = 'Inactive')
WHEN Count(a.Status) > 1 and a.Status In ('Active', 'Inactive')
THEN (select top 1 a.Address1 from Address a where a.Status = 'Active')
END AS Address1
from Address a where Attendee_Id= 1 group by a.Status, Address1, a.EmpId
答案 0 :(得分:1)
如果我理解正确,您可以使用outer apply
:
select e.*, a.*
from employee e outer apply
(select top 1 a.*
from address a
where a.empId = e.empId
order by status, -- "Active" is before "Inactive"
addressId
) a;
答案 1 :(得分:0)
row_number方法
select * from
(
select *
, count(*) over (partition by e.EmpID) as cnt
, row_number() over (partition by e.EmpID
order by a.Status, a.AddressId) as rn
from employee e
join address a
on a.EmpID = e.EmpID
) tt
where tt.rn = 1