1. 查询各学生的年龄,通过年份来计算

    **
    练习时间函数之前,我们先看一下当前的时间
    image.png

    1. select s_name, s_birth, (year(now()) - year(s_birth)) as age from Student;

    结果截图
    image.png

    1. 查询各学生的年龄,通过出⽣⽇期来计算,当前⽉⽇ < 出⽣年的⽉⽇,年龄减⼀

    **

    1. select s_name, s_birth, timestampdiff(year, s_birth, now()) as age from Student;

    结果截图
    image.png

    1. 查询本周过生日的学生

    **

    1. select * from Student
    2. where week(s_birth) = week(now());

    结果截图(Empty Set)
    image.png

    1. 查询下周过生日的学⽣

    **

    1. select * from Student
    2. where week(s_birth) = week(now()) + 1;

    结果截图
    image.png

    1. 查询本⽉过⽣⽇的学⽣

    **

    1. select * from Student
    2. where month(s_birth) = month(now());

    结果截图
    image.png

    1. 按各科成绩进行排序,并显示排名,Score重复时保留名次空缺(难度等级:三颗星)

    **

    1. select a.s_id, a.c_id, a.s_score, count(b.s_score) + 1 as rank
    2. from Score a left join Score b
    3. on a.c_id = b.c_id and a.s_score < b.s_score
    4. group by a.s_id, a.c_id, a.s_score
    5. order by a.c_id, rank asc;

    结果截图
    image.png
    这里为我们显示排名信息提供了一种新的思路,之前我们都是通过定义变量的方式来显示

    1. 查询存在” 01 “课程但可能不存在” 02 “课程的情况(不存在时显示为null) (难度等级:三颗星)

    **

    1. select a.s_id, a.s_score as score1, b.s_score as score2 from
    2. (select s_id, s_score from Score where c_id = '01') as a
    3. left join
    4. (select s_id, s_score from Score where c_id = '02') as b
    5. on a.s_id = b.s_id;

    结果截图
    image.png

    1. 查询不存在” 01 “课程但存在” 02 “课程的情况

    **

    1. select * from Score
    2. where s_id not in (select distinct s_id from Score a where c_id = '01')
    3. and c_id = '02';

    结果截图
    image.png

    1. 查询大于每门课课程平均分的学生名单(难度等级:三颗星)

    **
    方案一

    1. select s.*, tmp.avg_score from Score s
    2. left join
    3. (select c_id, avg(s_score) as avg_score from Score group by c_id) as tmp
    4. on s.c_id = tmp.c_id
    5. where s.s_score > tmp.avg_score
    6. order by c_id, s_id;

    结果截图
    image.png
    方案二

    1. select a.s_id, a.c_id, a.s_score, avg(b.s_score) as avg_score from Score a
    2. left join Score b on a.c_id = b.c_id
    3. group by a.s_id, a.c_id, a.s_score
    4. having a.s_score > avg_score
    5. order by c_id, s_id;

    结果截图
    image.png
    方案一相对来说逻辑上好理解一些,方案二如果理解了前面的第16题,这种写法也就好理解了;面试的时候曾被问到过这道题目,结果没答上来,见鬼;如果使用了group by操作,那having就扮演了where的角色
    **

    1. 查询在同一个月份过生日的人数

    **

    1. select month(s_birth) as birthday, count(*) as num from Student
    2. group by birthday;

    结果截图
    image.png