select *,datediff(year,sage,getdate()) as '年龄' from student
粗略算法
select *,datediff(day,sage,getdate())/365 as '年龄' from student
具体算法
--46.1 只按照年份来算
select* , datediff(yy , sage , getdate()) [年龄]from student?
--46.2 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一
select* , casewhenright(convert(varchar(10),getdate(),120),5)
--47、查询本周过生日的学生
思路:将学生出生日期的年换成今年,然后加上具体日期,再和今天比较,如果为0,就是本周,如果为-1,就是下周,如果为1,就是上周。
select * fromstudent
where datediff(week,convert(varchar,datepart(yy,getdate()))+right(convert(varchar(10),sage,120),6),getdate())=0
select*from student wheredatediff(week,datename(yy,getdate()) +right(convert(varchar(10),sage,120),6),getdate()) =0
--48、查询下周过生日的学生
select * fromstudent
where datediff(week,convert(varchar,datepart(yy,getdate()))+right(convert(varchar(10),sage,120),6),getdate())=-1
select*from student wheredatediff(week,datename(yy,getdate()) +right(convert(varchar(10),sage,120),6),getdate()) =-1
--49、查询本月过生日的学生
思路:把学生的出生日期的年换成今年,然后判断月是否在当前月。为0就是本月,为1就是上月,为-1就是下月。
select * fromstudent
where datediff(mm,convert(varchar,datepart(yy,getdate()))+right(convert(varchar(10),sage,120),6),getdate())=0
select*from student wheredatediff(mm,datename(yy,getdate()) +right(convert(varchar(10),sage,120),6),getdate()) =0
--50、查询下月过生日的学生
select * fromstudent
where datediff(mm,convert(varchar,datepart(yy,getdate()))+right(convert(varchar(10),sage,120),6),getdate())=-1
select*from student wheredatediff(mm,datename(yy,getdate()) +right(convert(varchar(10),sage,120),6),getdate()) =-1
总结:
1.一种是先组合成一个总的记录集合,然后再进行GROUP BY或者ORDER BY等其他操作;另一种是分别先对小的记录集合进行其他操作,然后再组合到一起成为最终的一个记录集合。
2.针对排序,有三种情况:
RANK()OVER():排名1,1,3——保留
DENSE_RANK()OVER:排名1,1,2——不保留
ROW_NUMBEROVER():排名1,2,3——没有同排名的
3.有关日期的计算,一是要注意东西方对星期开始的差异,最好是使用SET DATEFIRST 1来人为的设定每周开始为星期一。二是要注意年、月、日三个元素的分别调整。三是要注意在调整过程中数据类型的变换。