sql - 如何从出生日期计算年龄(年.月格式)

标签 sql sql-server

我写了一个查询,但它只返回几年,但我也需要几个月。以下是我编写的查询:

select cast(datediff(DAY, '2000-06-01 10:00:01', getDate() -1) / (365.23076923074) as varchar) as 'Age'

最佳答案

试试这个:

declare @DateOfBirth date= '1999-06-1'

Select AgeYears=DATEDIFF(year,@DateOfBirth ,getdate())- CASE WHEN MONTH(getdate())*100+DAY(getdate())<MONTH(@DateOfBirth)*100+DAY(@DateOfBirth) then 1 else 0 end
    ,AgeMoanths=(DATEDIFF(month,@DateOfBirth,getdate())  - CASE WHEN DAY(getdate())<DAY(@DateOfBirth) THEN 1 ELSE 0 END ) % 12
    ,Agedays=DATEDIFF (day,dateadd(month,(DATEDIFF(month,@DateOfBirth,getdate())  - CASE WHEN DAY(getdate())<DAY(@DateOfBirth) THEN 1 ELSE 0 END )  ,@DateOfBirth) ,getdate())

关于sql - 如何从出生日期计算年龄(年.月格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048923/

相关文章:

sql - MySQL 在 FUNCTION 中返回 GROUP_CONCAT

mysql - 表创建逻辑

java - 使用 JDBC 连接 SQL Server 2012 和 Java

sql - SQL Server 中表提示的用途是什么?

c# - VB.NET SQL Server 查询到 LINQ

mysql - SQL:查询多个表,仅查询一个表的最新结果,查询另一个表的所有结果

sql - CROSS APPLY vs OUTER APPLY速度差

sql - 从 Sql 服务器中的 where 子句中排除函数

sql - 是否可以防止 ORDS 转义我的 GeoJSON?

c# - 导入 excel 文件并比较两个表的重复数字