如何从不在1NF的表中获取最新的唯一记录?

时间:2016-04-29 16:04:38

标签: sql-server-2008 tsql

我正在尝试创建一个返回员工姓名,部门,主管和当前状态的查询。但是,该表包含历史记录以及每位员工的当前记录,包括他们拥有的每个主管,每个部门等的记录。

如何获得每位员工的最新记录?我试图简单地选择MAX(Effective_Date)列,仅拉取最后一条记录。但是,这并不总是适用于数据集,因为每条记录都有员工的ID,以及记录的ID

以下是全表设置的示例:Filedropper.com/exampledata

这是我现有代码的一个例子。

use ws_er;
select
od.Master_org_dim_id
,od.Member_Last_Name + ', ' + od.Member_First_Name as [Associate Name]
,od.Member_Role as [Tier]
,od.Member_Status as [Status]
,sod.member_last_name + ', ' + sod.member_First_name as [Supervisor Name]
,MAX(od.Effective_Date) as [Effective Date]
,COUNT(od.Master_org_dim_id) as [count]

from Organization_Dim as od
inner join organization_dim as sod on sod.org_dim_id = od.supervisor_dim_id

group by
od.Master_org_dim_id
,od.Member_Last_Name + ', ' + od.Member_First_Name
,od.Member_Role
,od.Member_Status
,sod.member_last_name + ', ' + sod.member_First_name

order by [associate name] desc

2 个答案:

答案 0 :(得分:1)

select * 
from 
( select * 
       , row_number() over (partition by od.Master_org_dim_id,    
                                         od.Member_Last_Name,   
                                         od.Member_First_Name 
                                order by od.Effective_Date desc) as rn 
       , count(od.Master_org_dim_id) over (partition by od.Master_org_dim_id,  
                                                        od.Member_Last_Name,  
                                                        od.Member_First_Name) as count
from Organization_Dim 
) odr
join organization_dim as sod 
  on sod.org_dim_id = odr.supervisor_dim_id
 and odr.rn = 1

但这只是一个不完全未定义的条件

on sod.org_dim_id = odr.supervisor_dim_id

我怀疑你需要得到想象并确定日期的主管,但这应该让你开始。即便如此,您也可以返回零或更多的主管。

如果输入的员工姓名不同,则会中断。我不需要告诉你这个数据设计不是最优的。

答案 1 :(得分:0)

您可以加入子查询,在该子查询中获取每个员工ID的最大日期,然后将日期用于该子查询。像这样:

use ws_er;
select
od.Master_org_dim_id
,od.Member_Last_Name + ', ' + od.Member_First_Name as [Associate Name]
,od.Member_Role as [Tier]
,od.Member_Status as [Status]
,sod.member_last_name + ', ' + sod.member_First_name as [Supervisor Name]
,mxd.EffectiveDate as [Effective Date]
,COUNT(od.Master_org_dim_id) as [count]

from Organization_Dim as od
inner join organization_dim as sod on sod.org_dim_id = od.supervisor_dim_id
inner join (select Master_org_dim_id, max(Effective_Date) EffectiveDate from Organization_Dim group by Master_org_dim_id) as mxd
on od.Master_org_dim_id = mxd.Master_org_dim_id

group by
od.Master_org_dim_id
,od.Member_Last_Name + ', ' + od.Member_First_Name
,od.Member_Role
,od.Member_Status
,sod.member_last_name + ', ' + sod.member_First_name
,mxd.EffectiveDate

order by [associate name] desc

未经测试,但应该做到这一点,或者至少指出正确的方向