你如何为每个ID选择第n行?

时间:2014-07-30 10:18:01

标签: sql-server

如何为每个ID选择所有第n行? 我的表看起来有点像这样:

    ID  fName   data
     1  Hari    20
     1  Hari    30
     2  John    89
     2  John    38
     2  John    55

在这种情况下,如何为每个ID选择所有第二行?

结果如下:

    ID  fName   data
     1  Hari    30
     2  John    38 

3 个答案:

答案 0 :(得分:5)

这将有助于SQL SERVER 2012:

SELECT ID,  FNAME,   DATA FROM 
(
     SELECT TEST_DATA.*, 
     ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ORDER_BY_CONDITION) AS RANK
     FROM TEST_DATA
) T 
WHERE T.RANK=2

按条件更改订单(相应地按ORDER_BY_CONDITION

SQL SERVER 2012的小提琴:http://sqlfiddle.com/#!6/f59a1/3

编辑:对于多个表格,您可以尝试使用CTE,如同小提琴:http://sqlfiddle.com/#!6/8a5b1d/10

答案 1 :(得分:0)

以下查询是否适合您? (替换<tablename><datecolumn>名称)

SELECT tbl.*
FROM <tablename> tbl
INNER JOIN
(
    SELECT
        ID,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY <datecolumn>) rn
    FROM <tablename>
) row_numbers
ON tbl.ID = row_numbers.ID AND tbl.<datecolumn> = row_numbers.<datecolumn> AND row_numbers.rn = 2;

<强>参考

ROW_NUMBER function on MSDN

答案 2 :(得分:0)

使用CTEROW_NUMBER() ...

;
WITH    cteData ( ID, fName, data )
          AS ( SELECT   ID ,
                        fName ,
                        data ,
                        ROW_NUMBER() 
                         OVER ( PARTITION BY ID ORDER BY DateField ) AS 'rowNum' 
FROM tblName
             )
    SELECT  ID ,
            fName ,
            data
    FROM    cteData
    WHERE   rowNum = 2--Im assuming 2 from the data presented in question