超经典SQL练习,当你全部弄透,你的SQL已小成( 五 )


--要求输出课程号和选修人数,查询结果按人数降序排列,若人数相同,按课程号升序排列
select S# from SC
group by S#
having COUNT(C#)>=2
--38. 检索至少选修两门课程的学生学号
select S# from SC
group by S#
having count(C#)=(select distinct COUNT(0)a from Course)
--39. 查询选修了全部课程的学生信息
select S#,datediff(yy,Sage,GETDATE())年龄 from Student
--40. 查询各学生的年龄,只按年份来算
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
--41. 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一
--方法是把时间转化成 Int 格式来做条件比较大小,判断是否超期,
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
--42. 查询本周过生日的学生
--方法:采取将生日转化为当年日期,再转化为本年中的第几个星期进行判断搜出结果
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
--43. 查询下周过生日的学生
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
--44. 查询本月过生日的学生
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
--45. 查询下月过生日的学生




推荐阅读