我有一个包含这些值的出生日期字段:
28 Juillet 1982 (I want this one to be excluded)
09/16/1981 (This one will be used)
(empty, should be excluded)
03/19/1953 (This one will be used)
我想获取 mm/dd/yyyy 日期的平均年龄。现在我的查询是:
SELECT AVG(NULLIF(YEAR(NOW())-YEAR(Birthdate), 0)) AS AvgAge FROM `User`
我也尝试过:
SELECT AVG( YEAR(NOW())-YEAR(Birthdate) ) AS AvgAge FROM `User`
但结果总是相同的:NULL
每个 100% 数字的 id_user 都有正确的 mm/dd/yyyy 出生日期,所以我也尝试过:
SELECT AVG(CASE WHEN id_user >=0 THEN YEAR( NOW( ) ) - YEAR( Birthdate ) ELSE NULL END ) AS AvgAge FROM `User`
还有:
SELECT AVG(CASE WHEN CEIL(id_user) = id_user THEN YEAR( NOW( ) ) - YEAR( Birthdate ) ELSE NULL END ) AS AvgAge FROM `User`
仍然NULL...
你知道为什么会这样吗?
也许是我的一个简单错误,但我无法弄清楚。
谢谢!
最佳答案
阅读此内容:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-types.html
我认为类型可能不正确。
Although MySQL tries to interpret values in several formats, date parts must always be given in year-month-day order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98').
关于mysql - AVG 返回 null 但不应返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126934/