我有这样的一个数据表结构
ID 主键
UserID 用户ID
DepartmnentID 部门ID
ExamScore 考试成绩
其余字段等等。。。。
一个人可以参加多次考试
我只需要把这个人的最好成绩的那条记录拿出来就行
希望出来的这个结果集还是这个表结构
但是按照成绩的倒序 来排,且一个人只拿他的最高分就行
相应的SQL 要怎么写?
------解决思路----------------------
select * from table1 where examScore = (selece max(examscore) from table1 where userId =用户id) ; 你可以试试,不知道对不对
------解决思路----------------------
select ID,UserID,DepartmnentID,ExamScore from
(select * ,rn=row_number() over (partition by UserID order by ExamScore desc) a
where rn=1
order by ExamScore desc
------解决思路----------------------
用CROSS APPLY最合适了。
/* 测试数据
WITH ExamTable(ID,UserID,DepartmentID,ExamScore)AS(
SELECT 1,1,1,74 UNION ALL
SELECT 2,1,1,86 UNION ALL
SELECT 3,2,2,91 UNION ALL
SELECT 4,1,1,69
)*/
SELECT e.*
FROM (-- 如果有单独的用户表最好,替换掉这个子查询
SELECT DISTINCT UserID
FROM ExamTable
) u
CROSS APPLY (
SELECT TOP 1 *
FROM ExamTable
WHERE UserID = u.UserID
ORDER BY ExamScore DESC
) e
ORDER BY ExamScore DESC
ID UserID DepartmentID ExamScore
----------- ----------- ------------ -----------
3 2 2 91
2 1 1 86