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

时间:2014-06-09 09:21:23

标签: sql sql-server sql-server-2008

我有一个名为tblHumanResources的表,我想在其中获取所有行的集合,这些行只包含effectiveDate列中每个不同字段的2行(按升序排序):< / p>

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

等等。

非常感谢任何帮助。

6 个答案:

答案 0 :(得分:1)

尝试使用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

没有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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

从tblHumanResources

中选择前2 *

答案 3 :(得分:0)

对于表中的每条记录,您选择在effectiveDate列中具有相同值的前2行作为主选择中的当前记录,并且只有当它的empId位于子选定行中时才获取记录查询。

select * from tblHumanResources tt
where tt.empID in (select top 2 tt2.empID from tblHumanResources tt2 
                   where tt2.effectiveDate= tt.effectiveDate)

答案 4 :(得分:0)

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

答案 5 :(得分:0)

;WITH CTE AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY effectiveDate ORDER BY effectiveDate ASC) AS RN
FROM tblHumanResources)
SELECT *
FROM CTE
WHERE RN <= 2