为了账号安全,请及时绑定邮箱和手机立即绑定

sql server 取每一个学生多个科目当中分数最高的记录

标签:
SQL Server

同表当中,取每一个学生多个科目当中分数最高的记录(name,sub,scores)

WITH tmp AS(SELECT stuid,sub,scores,ROW_NUMBER() OVER (PARTITION BY stuid ORDER BY scores DESC) as num 
  FROM score
  )SELECT * FROM tmp WHERE num<=1

同表当中,取每一个科目最高的记录(name,sub,scores):

WITH tmp AS(SELECT stuid,sub,scores,ROW_NUMBER() OVER (PARTITION BY sub ORDER BY scores DESC) as num 
  FROM score
  )SELECT * FROM tmp WHERE num<=1

两表当中,取每一个学生多个科目当中分数最高的记录(id,name,sub,scores):

SELECT a.id,a.name,b.sub,b.scores FROM students AS a JOIN score AS b ON a.id=b.stuid JOIN score AS c ON b.stuid=c.stuid 
GROUP BY a.id,a.name,b.name,b.scores HAVING b.scores=MAX(c.scores) 
----------------------------------------------------------------------------
或者
WITH tmp AS(SELECT a.id,a.name,b.sub AS sub,b.scores,ROW_NUMBER() OVER (PARTITION BY b.stuid ORDER BY scores DESC) as num 
  FROM students AS a JOIN score AS b ON a.id=b.stuid
  )SELECT * FROM tmp WHERE num<=1

两表当中,取每一个科目最高的记录(id,name,sub,scores):

SELECT a.id,a.name,b.sub,b.scores FROM students AS a JOIN score AS b ON a.id=b.stuid JOIN score AS c ON b.sub=c.sub
GROUP BY a.id,a.name,b.sub,b.scores HAVING b.scores=MAX(c.scores) 
----------------------------------------------------------------------------
或者
WITH tmp AS(SELECT a.id,a.name,b.sub AS sub,b.scores,ROW_NUMBER() OVER (PARTITION BY b.sub ORDER BY scores DESC) as num 
  FROM students AS a JOIN score AS b ON a.id=b.stuid
  )SELECT * FROM tmp WHERE num<=1

mysql:
两表当中,取每一个科目最高的记录(id,name,sub,scores):

SELECT d.name,c.stuid,c.scores,c.sub,c.num  FROM (SELECT stuid,scores,sub,(SELECT COUNT(*) FROM score AS b WHERE a.stuid=b.stuid AND a.scores<=b.scores) AS num 
FROM score AS a GROUP BY stuid,scores,sub) AS c JOIN students AS d ON c.stuid=d.id WHERE c.num<=1

mysql:
两表当中,取每一个学生多个科目当中分数最高的记录(id,name,sub,scores):
(这条语句的问题是:当同一个科目的最高分有两个或两个以上时,数据就会被过滤掉,不知道怎么解决……)

SELECT d.name,c.stuid,c.scores,c.sub,c.num  FROM (SELECT stuid,scores,sub,(SELECT COUNT(*) FROM score AS b WHERE a.sub=b.sub AND a.scores<=b.scores) AS num 
FROM score AS a GROUP BY stuid,scores,sub) AS c JOIN students AS d ON c.stuid=d.id WHERE c.num<=1
点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消