使用MONTHS_BETWEEN()选择计数平均年龄

时间:2014-04-27 10:45:04

标签: mysql sql

例如。我的表EMPLOYEE

//EMPLOYEE
E#      NAME      DOB
----------------------------
1       JOHN     13-10-1965
2       SITI     20-02-1968
3       ALI      31-03-1977

所以我的问题是计算他们每个人的年龄,然后一起总结,然后除以员工人数来计算员工的平均年龄。

我目前的陈述。

SELECT DOB from employee where ..
// DIVIDE COUNT(*) FROM EMPLOYEE 

2 个答案:

答案 0 :(得分:0)

试试这个:

select sum(age)/count(*) as AVG from (SELECT Name,YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age 
  FROM EMPLOYEE )t

答案 1 :(得分:0)

你可以这样做

SELECT 
avg(age) as  average_dob
from
(
  select
  TIMESTAMPDIFF(YEAR,DOB,NOW()) AS age 
  from 
  Employee
)t;

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff

<强> DEMO