如何查找具有相同 id 的员工的最新等级。 我的 table 是这样的:
+----+-------+-------+
| 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
最佳答案
按 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
关于mysql - SQL查询员工最新等级,每个员工有多条具有相同id的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747295/