0

How to find the latest grade of an employee has the same id. my table is like:

+----+-------+-------+
| ID |  NAME | GRADE | 
| 1  |  ANN  |  A0   | 
| 1  |  ANN  |  A3   |  
| 2  |  JOE  |  B1   | 
| 3  | KIM   |  B3   | 
| 2  | JOE   |  B2   | 
| 3  | KIM   |  C1   | 
| 3  | KIM   |  C3   | 
+----+-------+-------+

How to find the latest grade of ann, Kim, and joe

my output is like:

name latestgrade
ann  A3
joe  B2
kim  C3
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Anu Antony
  • 125
  • 1
  • 2
  • 12

2 Answers2

0

try row_number

;with cte 
as
(
 SELECT
   SeqNo = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY 
SUBSTRING(GRADE,1,1) desc,CAST(SUBSTRING(GRADE,2,LEN(GRADE)) AS INT) DESC),
       *
       FROM YourTable
    )
    SELECT
    * 
    FROM CTE
    WHERE SeqNo = 1

If you wish to insert the above result into a new table, just write a insert into before the select

;with cte 
    as
    (
     SELECT
       SeqNo = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY 
    SUBSTRING(GRADE,1,1) desc,CAST(SUBSTRING(GRADE,2,LEN(GRADE)) AS INT) DESC),
           *
           FROM YourTable
        )
insert into MyNewTable
        SELECT
        * 
        FROM CTE
        WHERE SeqNo = 1
Jayasurya Satheesh
  • 7,826
  • 3
  • 22
  • 39
0

Give a row number group by ID and order by the descending order of Grade

Sql Server Query

;with cte as(
    select [rn] = row_number() over(
        partition by [ID]
        order by len([GRADE]) desc, [GRADE] desc
    ), *
    from [your_table_name]
)
select [ID], [NAME], [GRADE]
from cte
where [rn] = 1;

demo

MySql Query

select t1.`ID`, t1.`NAMME`, t1.`GRADE` from (
    select `ID`, `NAME`, `GRADE`, (
        case `ID` when @curA 
        then @curRow := @curRow + 1 
        else @curRow := 1 and @curA := `ID` end 
    ) as `rn` 
    from `your_table_name` t, 
    (select @curRow := 0, @curA := '') r 
    order by `ID`, length(`GRADE`) desc, `GRADE` desc
)t1 
where t1.`rn` = 1;

demo

Ullas
  • 11,450
  • 4
  • 33
  • 50