SQL进阶练习题46-50

SQL进阶练习题46-50

大背景和建表、插入语句就不啰嗦了,参考第一篇

四张表概要:

  1. 学生表
    student(sid,sname,sage,ssex) --sid 学生编号,sname 学生姓名,sage 出生年月,ssex 学生性别
  2. 课程表
    course(cid,cname,tid) --cid 课程编号,cname 课程名称,tid 教师编号
  3. 教师表
    teacher(tid,tname) --tid 教师编号,tname 教师姓名
  4. 成绩表
    sc(sid,cid,score) --sid 学生编号,cid 课程编号,score 分数
    为了方便查看,我把四个表截了图:


    student

    course

    teacher

    sc

题目:

  1. 查询各学生的年龄,只按年份来算
  2. 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一
  3. 查询本周过生日的学生
  4. 查询下周过生日的学生
  5. 查询本月过生日的学生
  6. 查询下月过生日的学生

sql

查询各学生的年龄,只按年份来算

select sname,substring(sage,0,10)
from student;

按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

select *,(case when convert(int,'1'+substring(CONVERT(varchar(10),Sage,112),5,8))
<convert(int,'1'+substring(CONVERT(varchar(10),GETDATE(),112/*112是将格式转化为yymmdd*/),5,8))
then datediff(yy,Sage,GETDATE())
else datediff(yy,Sage,GETDATE())-1
end)age
from student;

查询本周过生日的学生

select *,(case when datename(wk,convert(datetime,(convert(varchar(10),year(GETDATE()))+substring(convert(varchar(10),Sage,112),5,8))))=DATENAME(WK,GETDATE())
then 1 else 0 end)生日提醒
from student;

查询下周过生日的学生

select *,(case when datename(wk,convert(datetime,(convert(varchar(10),year(GETDATE()))+
substring(convert(varchar(10),Sage,112),5,8))))=DATENAME(WK,GETDATE())+1
then 1 else 0 end)生日提醒
from student;

查询本月过生日的学生

select *,(case when month(convert(datetime,(convert(varchar(10),year(GETDATE()))+substring(convert(varchar(10),Sage,112),5,8))))=month(GETDATE())
then 1 else 0 end)生日提醒
from student;

查询下月过生日的学生

select *,(case when month(convert(datetime,(convert(varchar(10),year(GETDATE()))+substring(convert(varchar(10),Sage,112),5,8))))=month(GETDATE())+1
then 1 else 0 end)生日提醒
from student;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容