从结果集中获取第一条记录

时间:2012-02-14 09:21:52

标签: sql linq tsql

enter image description here

我想只选择突出显示的记录。我怎样才能在sql中完成,最好是在linq中。有一个单独的表EmpEmployeeIDPK。 这是我的表的架构

enter image description here

4 个答案:

答案 0 :(得分:2)

我可能会离开,但我相信以下声明满足您的要求

SELECT *
FROM   (
         SELECT e.EmployeeID, h.FromDate, h.ToDate
                , rn = ROW_NUMBER() OVER (PARTITION BY e.EmployeeID ORDER BY DesignationID DESC)
         FROM   employee e
                INNER JOIN history h ON h.EmployeeID = e.EmployeeID
       ) eh
WHERE rn = 1

答案 1 :(得分:2)

尝试:

select * from
(select t.*, 
        row_number() over (partition by EmployeeID order by FromDate) as rn) sq
where rn = 1

答案 2 :(得分:1)

不确定你在寻找什么,但尝试这样的事情(不需要子查询,并且应该适用于大多数DBMS,尽管它看起来像是在运行SQL Server):

select t1.DisignationHistoryIDs, t1.employeeId, t1.fromDate from history t1
left join history t2
on t1.employeeId = t2.employeeId and t1.fromDate > t2.fromDate
where t2.fromDate is null

这应该可以获得最早的fromDate。要获得最新的日期,只需更改>的{​​{1}}。

答案 3 :(得分:1)

无法确切地看到你的要求。突出显示的ID只是唯一的事件。所以你可以通过以下方式轻松完成:

SELECT DISTINCT EmployeeID FROM MyTable
相关问题