简体   繁体   English

从Microsoft SQL Server 2008的列中的每个不同字段中获取前2行

[英]Get top 2 rows from each distinct field in a column in Microsoft SQL Server 2008

I have a table named tblHumanResources in which I want to get the collection of all rows which consists of only 2 rows from each distinct field in the effectiveDate column (order by: ascending): 我有一个名为tblHumanResources的表,在该表中我要获取所有行的集合,该行仅包含来自effectiveDate列中每个不同字段的2行(排序方式:升序):

tblHumanResources Table tblHumanResources

| empID | effectiveDate |  Company | Description
| 0-123 |    2014-01-23 | DFD Comp | Analyst
| 0-234 |    2014-01-23 | ABC Comp | Manager
| 0-222 |    2012-02-19 | CDC Comp | Janitor
| 0-213 |    2012-03-13 | CBB Comp | Teller
| 0-223 |    2012-01-23 | CBB Comp | Teller

and so on. 等等。

Any help would be much appreciated. 任何帮助将非常感激。

Try to use ROW_NUMBER() function to get N rows per group: 尝试使用ROW_NUMBER()函数获取每个组N行:

SELECT * 
FROM
  (
     SELECT t.*,
            ROW_NUMBER() OVER (PARTITION BY effectiveDate 
                               ORDER BY empID) 
            as RowNum
     FROM tblHumanResources as t

  ) as t1
WHERE t1.RowNum<=2
ORDER BY effectiveDate

SQLFiddle demo SQLFiddle演示

Version without ROW_NUMBER() function assuming that EmpId is unique during the day: 没有ROW_NUMBER()函数的版本假定EmpId在一天中是唯一的:

SELECT * 
FROM tblHumanResources as t
WHERE t.EmpID IN (SELECT TOP 2
                         EmpID 
                    FROM tblHumanResources as t2
                   WHERE t2.effectiveDate=t.effectiveDate
                   ORDER BY EmpID)
ORDER BY effectiveDate

SQLFiddle demo SQLFiddle演示

SELECT TOP 2
        *
FROM    ( SELECT    * ,
                    ROW_NUMBER() OVER ( PARTITION BY effectiveDate ORDER BY effectiveDate ASC ) AS row_num
          FROM      tblHumanResources
        ) AS rows
WHERE   row_num = 1

从tblHumanResources中选择前2个*

For each record in the table you select the top 2 rows with the same value in effectiveDate column as the current record in the main select and get the record only if it's empId is in the selected rows in the sub query. 对于表中的每个记录,您都选择了有效日期列中与主选择中的当前记录具有相同值的前2行,并且仅当它的empId位于子查询的所选行中时才获取该记录。

select * from tblHumanResources tt
where tt.empID in (select top 2 tt2.empID from tblHumanResources tt2 
                   where tt2.effectiveDate= tt.effectiveDate)
SELECT  TOP 2 *
FROM    (
         SELECT *, ROW_NUMBER() OVER (PARTITION BY effectiveDate ORDER BY effectiveDate ASC) AS row_number
         FROM   tblHumanResources
        ) AS rows
WHERE   row_number = 1
;WITH CTE AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY effectiveDate ORDER BY effectiveDate ASC) AS RN
FROM tblHumanResources)
SELECT *
FROM CTE
WHERE RN <= 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM