在SQL中计算年龄 [英] To calculate age in SQL

查看:1399
本文介绍了在SQL中计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要计算出生日期的DOB月份和年龄。



DOB:

Need to calculate DOB month and age from given date of birth.

DOB:

1988-10-20

(YYYY-MM-DD)



我需要输出



(YYYY-MM-DD)

I need output as

10 and age of(1988-10-20) 





我尝试过使用它,但我没有得到正确的输出。





I have tried using it, but i coudn't get proper output.

SELECT (DATEDIFF(MONTH,'1988-10-20',getdate()))-(DATEDIFF(YEAR,'1988-10-20',GETDATE())*12)  AS Smonth





但我输出为-1,



我需要输出为10.



我尝试过:





But iam getting output as -1,

I need to get output as 10.

What I have tried:

SELECT (DATEDIFF(MONTH,'1988-10-20',getdate()))-(DATEDIFF(YEAR,'1988-10-20',GETDATE())*12)  AS Smonth

推荐答案

请参阅此帖子的解决方案2 如何计算sql中出生日期的年龄 [ <一个href =https://www.codeproject.com/Questions/400138/How-to-calculate-age-from-date-of-birth-in-sqltarget =_ blanktitle =New Window> ^ ]
See Solution 2 to this post How to calculate age from date of birth in sql[^]


DECLARE @DOB Date='07/03/1993';

SELECT CAST(ROUND((DATEDIFF(DAY,@DOB,GETDATE())/365.0),0) AS INT) AS AGE

OUTPUT:-
----
AGE
----
25


select convert(nvarchar(max),Month('1988-10-20'))+' and ' + convert(nvarchar(max), DATEDIFF(year, '1988-10-20',getdate()))+' age of '+'1988-10-20' as Age 





输出

----------------

10和30年龄1988-10-20



Output
----------------
10 and 30 age of 1988-10-20


这篇关于在SQL中计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆