计算从当月开始的年龄

时间:2015-12-11 16:08:33

标签: mysql date date-difference

我有以下代码来计算从今天起生效的人的出生日期

    SELECT application.applicationLastName, application.applicationFirstName, application.applicationDoB, 
ROUND(DATEDIFF(NOW(), applicationDoB) / 365.2425,1) AS age, application.applicationID, application.applicationAcknowledged, application.applicationContacted, application.applicationDate
FROM application
ORDER BY application.applicationDate ASC 

然而,我被要求从本月1日开始计算他们的年龄并尝试过

SELECT application.applicationLastName, application.applicationFirstName, application.applicationDoB, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS CURMONTH, 
ROUND(DATEDIFF(CURMONTH(), applicationDoB) / 365.2425,1) AS age, application.applicationID, application.applicationAcknowledged, application.applicationContacted, application.applicationDate
FROM application
ORDER BY application.applicationDate ASC

但是我收到以下错误:调用本机函数时参数计数不正确' DATEDIFF'

2 个答案:

答案 0 :(得分:0)

您不应该使用CURMONTH()。而是将今天的日期格式化为本月1日。

使用以下查询:

SELECT application.applicationLastName, application.applicationFirstName, application.applicationDoB, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) AS CURMONTH, 
ROUND(DATEDIFF(DATE_FORMAT(NOW() ,'%Y-%m-01'), applicationDoB) / 365.2425,1) AS age, application.applicationID, application.applicationAcknowledged, application.applicationContacted, application.applicationDate
FROM application
ORDER BY application.applicationDate ASC

答案 1 :(得分:0)

您正在使用: DATEDIFF(CURMONTH(),applicationDoB)

你的代码中的

。但是CURMONTH()只给你当前日期的月份,而applicationDoB给你一个完整的日期。您需要用对应于完整日期的表达式(当前月份的第1个)替换CURMONTH()。