sql-server-2005 - 如何获取两个日期的月数和天数

标签 sql-server-2005 tsql

我有两个表:

AgeMilestones //Represents available timespans
Id int     
Description varchar //(newborn, 1 month old, 2 month old, etc.)
NbrMonths int //( 0, 1, 2, etc.)
NbrDays int //(0, 1, 2, etc.)   


Child
Id int     
DateOfBirth DateTime  

我需要获取给定 child 当前年龄已过的年龄里程碑。问题是真正的一个月可以有 28 天、30 天或 31 天。因此,如果我将NbrMonths转换为天,我可能偶尔会休息几天。

是否有其他方法可以使用现有的表结构来更准确地执行此操作?

编辑:
我需要计算出年龄里程碑对应于 child 出生到今天之间存在的月数/天数(类似于下面的内容)。如果年龄里程碑可能是 3 个月又 15 天,或者 5 个月零 7 天,我就会被绊倒......

SET @Days = DateDiff(d,child.DateOfBirth, GetDate())  
SET @Months = DateDiff(m,child.DateOfBirth, GetDate()) 

SELECT * FROM AgeMileStone WHERE NbrMonths < @Months AND NbrDays < @Days 


诸如
之类的记录存在问题 年龄里程碑:
编号:4
描述:“5又1/2个月”
月份:5
天数:15

最佳答案

使用 datediff(month, DOB, getdate()) 非常容易

类似这样的事情:

declare @dob datetime = getdate() - 123; --born 123 days ago

select cast(datediff(month, @dob, getdate()) as varchar) + ' month old'
,cast(datediff(day, @dob, getdate()) as varchar) + ' days old'

更新

declare @dob datetime;
set @dob = getdate() - 125;

select 
datediff(month, @dob, getdate()) [Months], 
datediff(day, dateadd(month, datediff(month, @dob, getdate()), @dob), getdate()) [Offset Days]

关于sql-server-2005 - 如何获取两个日期的月数和天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3781162/

相关文章:

sql-server - XQuery/XPath 使用 sql 参数?

tsql - 查看SSRS报表生成的SQL查询的简单方法?

sql-server - 重命名索引的最佳方法

tsql - 如何计算SQL Server 2000 中对象的数量并获取其修改日期?

sql-server - SQL Server 代理作业超时

sql-server - Microsoft SQL Server - 谁创建了存储过程?

sql-server - 在 SQL Server Management Studio 中将持久计算列标记为 NOT NULL

java - SQL2005 的方言

c# - 性能 : should I make one or multiple queries to database

sql - 如何知道区域表中的父区域级别名称?