SQL查询最新级别的员工,每个员工都有几个具有相同ID的记录

时间:2017-12-11 06:06:44

标签: mysql sql-server

如何查找员工的最新成绩具有相同的ID。 我的桌子就像:

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

如何找到ann,Kim和joe的最新成绩

我的输出如下:

name latestgrade
ann  A3
joe  B2
kim  C3

2 个答案:

答案 0 :(得分:0)

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

如果您希望将上述结果插入到新表中,只需在选择

之前写入插入
;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

答案 1 :(得分:0)

按ID分列行号组,按等级

的降序排序

Sql Server查询

;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查询

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