例如:表a中有2个列number和birtyday,如何通过select语句计算出number为01的人的年龄?
sql中如何获取表中datetime类型的指定部分?
答案:3 悬赏:20
解决时间 2021-02-17 18:00
- 提问者网友:星空下的寂寞
- 2021-02-17 08:34
最佳答案
- 二级知识专家网友:何以畏孤独
- 2021-02-17 10:04
select datediff(year,Birthday,getdate()) as age from a where number='01'
--此句是以年份为依据,两个年份相减而得。
select case
when day(getdate())-day(Birthday)<0
then datediff(month,Birthday,getdate())/12-1
when day(getdate())-day(Birthday)>=0
then datediff(month,Birthday,getdate())/12
end
as age from a where number='01'
--此句是以月份为依据。
--得到准确的年龄计算:
select case
when DatePart(dy, getdate())-DatePart(dy, Birthday)<0
then datediff(year,Birthday,getdate())-1
when DatePart(dy, getdate())-DatePart(dy, Birthday)>=0
then datediff(year,Birthday,getdate())
end
as age from a where number='01'
--此句是以年份为依据,两个年份相减而得。
select case
when day(getdate())-day(Birthday)<0
then datediff(month,Birthday,getdate())/12-1
when day(getdate())-day(Birthday)>=0
then datediff(month,Birthday,getdate())/12
end
as age from a where number='01'
--此句是以月份为依据。
--得到准确的年龄计算:
select case
when DatePart(dy, getdate())-DatePart(dy, Birthday)<0
then datediff(year,Birthday,getdate())-1
when DatePart(dy, getdate())-DatePart(dy, Birthday)>=0
then datediff(year,Birthday,getdate())
end
as age from a where number='01'
全部回答
- 1楼网友:随心随缘不随便
- 2021-02-17 11:18
select number,birthday,nl=(datediff(yy,birthday,'2014-06-03')) from a
主要是找函数计算,以上也没有试,试一下行否。
- 2楼网友:白日梦制造商
- 2021-02-17 10:42
首先
as datetime后,肯定是带年月日的时间,不可能是你说的那种15:00:00:000
再一个,你传一个整型需要多次类型转换
declare @searchtime int = 1500000000 --输入查询时间
declare @var varchar(20)
declare @str varchar(20)
select @var=cast(@searchtime as varchar)
select @str=left(@var,2)+':'+substring(@var,3,2)+':'+substring(@var,5,2)+'.'+right(@var,3)
select convert(varchar,@str,114)最后这个结果也是个字符型的,如果你转成datetime型的,前边就会有1900-1-1了
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯