简体   繁体   中英

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 Table

| 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:

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

Version without ROW_NUMBER() function assuming that EmpId is unique during the day:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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