找到最小值

时间:2019-10-06 06:56:41

标签: sql sql-server database

我写了一个代码来查找学生的最低年龄,但这是行不通的。

SELECT 
  S.stuName,
  (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) AS AGE
FROM tblStudent S
WHERE (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) <= ALL   
        (SELECT(YEAR(GETDATE()) - YEAR(S.stuBirthdate))
            FROM tblStudent )

请问您可以帮助解决此问题吗?

4 个答案:

答案 0 :(得分:0)

尝试一下:

  SELECT 
    S.stuName,
    (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) AS AGE
  FROM tblStudent S
  WHERE stuBirthDate = (
    SELECT MAX(stuBirthdate) FROM tblStudent
  ) -- Get birthdate of youngest student

答案 1 :(得分:0)

尝试此查询

SELECT S.stuName, MIN(YEAR(GETDATE())-YEAR(S.stuBirthdate)) AS AGE FROM tblStudent S GROUP BY S.stuName

答案 2 :(得分:0)

别名使用错误。为子查询中的表指定一个单独的别名。当前,您将每个学生与他/她自己进行比较。

SELECT 
  S.stuName,
  (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) AS AGE
FROM tblStudent S
WHERE (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) <= ALL   
        (SELECT(YEAR(GETDATE()) - YEAR(t2.stuBirthdate))
            FROM tblStudent t2 );

答案 3 :(得分:0)

获取最低年龄的学生名单的最简单方法是使用SELECT TOP WITH TIESORDER BY

SELECT TOP (1) WITH TIES S.stuName,
       (YEAR(GETDATE()) - YEAR(S.stuBirthdate)) AS AGE
FROM tblStudent S
ORDER BY AGE ASC;