Use of Rank() and Partitioned by in SQL SERVER 2008

I have a Table Data like this

      EmpID         Code

      1                   A

      2                   B

     1                    C

     3                    D

     3                    E

     1                    F

     2                    G

     2                    H

     3                    I

     4                    J

    
I am expecting output as

  EmpID           Code

      1                   F

      1                   C

      2                   H

      2                   G

      3                   I

      3                   E

Only to show latest 2 data if any id has less than 2 data I don't want to show it (like Empid 4 ).

Thanks in a

September 3rd, 2015 1:52am

Declare @Test Table(EmpID int, Code char(1));
Insert @Test(EmpID, Code) Values
(      1,                   'A'),
(      2,                   'B'),
(     1,                    'C'),
(     3,                    'D'),
(     3,                    'E'),
(     1,                    'F'),
(     2,                    'G'),
(     2,                    'H'),
(     3,                    'I'),
(     4,                    'J');
;With cte As
(Select EmpID, Code, Row_Number() Over(Partition By EmpID Order By Code Desc) As rn,
   Count(*) Over(Partition By EmpID) As NbrRows
From @Test)
Select EmpID, Code
From cte
Where rn <= 2 And NbrRows > 1
Order By EmpID, Code;

Tom
Free Windows Admin Tool Kit Click here and download it now
September 3rd, 2015 2:17am

@Tom Cooper:

Thanks for your quick response.This is partially correct as the result shows like below (unlike the one I am expecting )

           1    C
           1    F
           2    G
           2    H
           3    E
           3    I

September 3rd, 2015 2:55am

Order By EmpID , Code DESC;
Free Windows Admin Tool Kit Click here and download it now
September 3rd, 2015 3:05am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics