我需要从出生日算起学生的最小年龄和平均年龄

I need to find the minimum and average age of students from the birth day

我有一个 table 'Students',其中包含 'DateOfBirth' 个学生。我需要一个 SQL statement,我可以在查询中使用它来为我提供 averageminimum ages 作为具有这些名称的字段?我不想添加一个年龄字段,我只是想要一个 SQL 声明,我可以复制并粘贴它 return 我需要的东西。

 SELECT MIN(DateOfBirth) AS Min Age, AVG(DateOfBirth) AS Avg Age FROM Students;

目前我找到的所有建议都要求我在 运行 时指定一个值,我不知道为什么?

SELECT *
FROM Students
GROUP BY DateOfBirth
ORDER BY DateOfBirth DESC


SELECT MIN(DateOfBirth) AS MinAges
FROM Students


SELECT AVG(DateOfBirth) AS AverageAges
FROM Students

使用聚合函数 AVG 和 MIN.. 您可以轻松地 google 顺便说一句...要计算年龄,您可以使用 getDate 函数并计算年龄 - 取决于您的 DateOfBirth 列格式..

  select AVG((getDate()-DateOfBirth)/365) as avgAge , 
   MIN ((getDate()-DateOfBirth)/365) as minAge 
  from Students

你应该先根据date of birth计算年龄,然后求平均年龄

Select AVG(Datediff("yyyy",DateOfBirth,getdate())) as AVGage from Students
Select MIN(Datediff("yyyy",DateOfBirth,getdate())) as MINage from Students

您还可以在一次查询中计算 avg,min

 Select AVG(Datediff("yyyy",DateOfBirth,getdate())) as AVGage , 
        MIN(Datediff("yyyy",DateOfBirth,getdate())) as MINage
        from Students

对于 MS ACCESS 数据库:

  • Now() 提供日期和时间
  • Date() 提供日期
  • Time() 提供时间

您可以使用 Date() 函数

 Select AVG(Datediff("yyyy",DateOfBirth,DATE())) as AVGage , 
        MIN(Datediff("yyyy",DateOfBirth,DATE())) as MINage
        from Students

这里是SQLFIDDLE FOR SQLSERVER: