0
点赞
收藏
分享

微信扫一扫

HQL,SQL刷题,尚硅谷

自由的美人鱼 03-01 14:00 阅读 3
sql数据库

目录


相关表数据:

1、student_info

2、course_info

3、score_info

题目及思路解析:

 查询结果排序&分组指定条件

1、查询学生的总成绩并按照总成绩降序排序

代码:

select
    stu_id,
    sum(score) total_score
from score_info
group by stu_id
order by total_score desc ;

思路分析:

结果:

2、按照如下格式显示学生的语文、数学、英语三科成绩,没有成绩的输出为0,按照学生的有效平均成绩降序显示 

代码:

方法1:

  select
      stu_id,
      sum(if(course_name='语文',score,0))  `语文`,
      sum(if(course_name='数学',score,0))  `数学`,
      sum(if(course_name='英语',score,0)) `英语`,
      count(*) `有效课程`,
      avg(score) `平均成绩`
  from score_info
  join course_info
  on score_info.course_id=course_info.course_id
  group by stu_id
  order by avg(score) desc;

思路:

方法2:

select
    t4.stu_id,
    nvl(t1.score,0) `语文`,
    nvl(t2.score,0) `数学`,
    nvl(t3.score,0) `英语`
from
(select
    stu_id,
    score
from score_info
where course_id='01'
)t1
full join

(select
    stu_id,
    score
from score_info
where course_id='02'
)t2
on t1.stu_id=t2.stu_id
full join
(select
    stu_id,
    score
from score_info
where course_id='03'
)t3
on nvl(t1.stu_id,t2.stu_id)=t3.stu_id
full join
(select
     stu_id,
    count(*) cnt,
    avg(score) avg_score
from score_info
group by stu_id
)t4
on coalesce(t1.stu_id,t2.stu_id,t3.stu_id)=t4.stu_id;

思路:

结果:

3、查询一共参加三门课程且其中一门为语文课程的学生的id和姓名

代码:

select
    t2.stu_id id,
    stu_name `姓名`
from
(
        select
        t1.stu_id
    from
        ( select
             stu_id,
             course_id
         from score_info
         where stu_id
         in (select
            stu_id
            from score_info
            join course_info
            on score_info.course_id=course_info.course_id
            where course_name='语文')
         )t1
    group by t1.stu_id
    having count(t1.course_id)=3
)t2
join student_info
on t2.stu_id=student_info.stu_id;

思路:

结果:

总结归纳:

知识补充:

   

举报

相关推荐

SQL,HQL刷题,尚硅谷

HQL刷题 50道

二刷jQuery(以尚硅谷入门)

JVM 尚硅谷

【尚硅谷】分页查询

ShardingSphere-尚硅谷

【尚硅谷】子查询

散列表,尚硅谷

0 条评论