我有一个SQL Server 2008表,其中包含Designationid
列和NewDesignationid
列。我想根据日期找到加入的指定ID。我不知道怎么做。
我的SQL Server表结构如下:
Designationid NewDesignationID UniqueID EmployeeID FromDate ToDate Comments ApprovedDate ModifiedBy ModifiedDate StatusID ChangeTo CreatedBy CreatedDate
12 25 258 1700 7/19/2011 7/27/2011 Designation Change 7/28/2011 61 7/28/2011 8 Executive - HR - Associate Executive - HR 61 7/28/2011
25 132 458 1700 7/28/2011 6/27/2012 Designation Change 6/28/2012 1700 6/28/2012 8 Associate Executive - HR To RMG Executive 1700 6/28/2012
25 132 510 1700 7/13/2012 8/2/2012 Designation Change 8/3/2012 1700 8/3/2012 8 Associate Executive - HR To RMG Executive 1700 8/3/2012
132 25 507 1700 6/28/2012 7/12/2012 Designation Change 7/13/2012 1896 7/13/2012 8 RMG Executive To Associate Executive - HR 1896 7/13/2012
我也想为每个特定的EmployeeId
做这件事。目前我已经为一个EmployeeId
。
答案 0 :(得分:2)
如果您只需要一行,则可以使用top 1
和order by ...
:
select top 1
Designationid, NewDesignationID
from <Table>
order by FromDate asc
如果您希望每位员工使用此功能,则可以使用row_number()
功能:
;with cte as (
select *, row_number() over(partition by EmployeeID order by FromDate asc) as rn
)
select
EmployeeID, Designationid, NewDesignationID
from cte
where rn = 1
你的问题中有一些微妙之处,而且这个问题在很多时候都有过讨论。其中一个问题是 - 如果你有2条具有相同FromDate和相同EmployeeID的记录,你想要获得两个记录,还是只想一个(如果你想要一个,那么你想要哪一个?)。如果你想要两个行,你可以使用这样的方法:
select
T.EmployeeID, T.Designationid, T.NewDesignationID
from <Table> as T
where
not exists (
select *
from <Table> as TT
where TT.EmployeeID = T.EmployeeID and TT.FromDate < T.FromDate
)
或
select
T.EmployeeID, T.Designationid, T.NewDesignationID
from <Table> as T
where
exists (
select 1
from <Table> as TT
group by TT.EmployeeID
having min(TT.FromDate) = T.FromDate
)
如果您只想要一个,可以使用row_number()
(见上文)或outer apply
:
select
T.EmployeeID, TT.Designationid, TT.NewDesignationID
from (select distinct TT.EmployeeID from <Table> as TT) as T
outer apply (
select top 1
TT.Designationid, TT.NewDesignationID
from <Table> as TT
where TT.EmployeeID = T.EmployeeID
order by TT.FromDate asc
) as TT
答案 1 :(得分:0)
尝试这种结构(你的样本不清楚)
SELECT EmployeeID,
min(FromDate)
FROM [EmployeeTable]
GROUP BY EmployeeID