我有一个名为tblHumanResources
的表,我想在其中获取行的集合,其中包含每个不同empID
的最新2行。 (最新的effectiveDate
)。
场景:我希望按empID排序条目集合,然后每个empID获得2行,其中包含最新的effectiveDate(如果按降序排序,则为effectiveDate的前2位)。
注意:我使用的是SQL Server 2008,我的表有数千行。
tblHumanResources
表
| empID | effectiveDate | Company | Description
| 0-123 | 1999-04-18 | DFD Comp | Analyst
| 0-234 | 2007-04-22 | ABC Comp | Manager
| 0-222 | 2012-02-19 | CDC Comp | Janitor
| 0-213 | 2009-05-03 | CBB Comp | Teller
| 0-223 | 2012-01-23 | CBB Comp | Teller
| 0-223 | 1999-05-27 | CBB Comp | Teller
| 0-123 | 2014-01-25 | DFD Comp | Analyst
| 0-234 | 1999-01-23 | ABC Comp | Manager
| 0-222 | 2014-12-13 | CDC Comp | Janitor
| 0-213 | 2014-02-12 | CBB Comp | Teller
| 0-223 | 2005-03-26 | CBB Comp | Teller
| 0-123 | 2005-02-05 | DFD Comp | Analyst
| 0-234 | 2014-05-18 | ABC Comp | Manager
| 0-222 | 2001-06-23 | CDC Comp | Janitor
| 0-213 | 2003-05-12 | CBB Comp | Teller
//and so on...
我想要显示如下内容:
| empID | effectiveDate | Company | Description
| 0-123 | 2014-01-25 | DFD Comp | Analyst
| 0-123 | 2005-02-05 | DFD Comp | Analyst
| 0-213 | 2014-02-12 | CBB Comp | Teller
| 0-213 | 2009-05-03 | CBB Comp | Teller
| 0-222 | 2014-12-13 | CDC Comp | Janitor
| 0-222 | 2012-02-19 | CDC Comp | Janitor
| 0-223 | 2012-01-23 | CBB Comp | Teller
| 0-223 | 2005-03-26 | CBB Comp | Teller
| 0-234 | 2014-05-18 | ABC Comp | Manager
| 0-234 | 2007-04-22 | ABC Comp | Manager
//and so on...
非常感谢任何帮助。
PS:我现在无法尝试你的代码,因为我的开发笔记本电脑不适合我。我会在几个小时后尝试您的答案,以便能够正确选择解决问题的答案。
谢谢。
答案 0 :(得分:2)
使用子查询
SELECT empID , effectiveDate , Company , [Description]
FROM
(
SELECT empID , effectiveDate , Company , [Description]
, ROW_NUMBER() OVER (PARTITION BY empID ORDER BY effectiveDate DESC) rn
FROM TableName
) A
WHERE rn <= 2
使用CTE
;WITH CTE
AS
(
SELECT empID , effectiveDate , Company , [Description]
, ROW_NUMBER() OVER (PARTITION BY empID ORDER BY effectiveDate DESC) rn
FROM TableName
)
SELECT empID , effectiveDate , Company , [Description]
FROM CTE
WHERE rn <= 2
不使用排名功能
SELECT t1.empID
,t1.effectiveDate
,t1.Company
,t1.[Description]
FROM TableName t1
WHERE t1.effectiveDate IN (SELECT TOP 2 effectiveDate
FROM TableName
WHERE empID = t1.empID
ORDER BY effectiveDate DESC)