[英]Get top 2 rows from each distinct field in a column in Microsoft SQL Server 2008
我有一個名為tblHumanResources
的表,在該表中我要獲取所有行的集合,該行僅包含來自effectiveDate
列中每個不同字段的2行(排序方式:升序):
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
等等。
任何幫助將非常感激。
嘗試使用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
沒有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
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個*
對於表中的每個記錄,您都選擇了有效日期列中與主選擇中的當前記錄具有相同值的前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.