Sql查询根据条件显示员工详细信息

时间:2018-05-28 10:29:51

标签: sql sql-server tsql

我有两个包含以下架构的表:

A)

--------------
Employee
-------------- 
EmpID  EmpName 
1      Abc

B)

Address 
-----------------------------------
AddressId EmpID  Address1 Status
-----------------------------------
1         1      Abc 1    Active
2         1      Abc 2    Inactive

我希望根据以下情况显示员工详细信息,例如EmpName,Address1:

  • a)如果Employee有一个活动和非活动地址,查询将显示 活动地址。
  • b)如果员工只有一个非活动地址,查询将显示非活动状态 地址。
  • c)如果Employee有多个活动或非活动地址,查询将显示数据库中的第一个地址,优先处理活动地址。

以下是我的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

2 个答案:

答案 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