不能使用MIN,MAX等SQL Server 2012

时间:2015-08-14 13:00:44

标签: sql-server aggregate-functions

我有这样的疑问:

 select 
      FirstName, LastName, BirthDate,
      GETDATE() AS [Today],
      CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) AS [Age]
FROM
      Employees
WHERE CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) >=55
ORDER BY LastName ASC

我想找到最大,最小和最平均的年龄,我想我能做到这一点,但显然我做不到。如何使这项工作?

 select 
     FirstName, LastName, BirthDate,
     GETDATE() AS [Today],
     CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) AS [Age],
     MIN (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT)
FROM
     Employees
WHERE 
     CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) >=55
ORDER BY 
     LastName ASC

错误:

  

Msg 195,Level 15,State 10,Line 5
  'MIN'不是公认的内置函数名称。

3 个答案:

答案 0 :(得分:1)

这是我找到的解决方案。感谢大家的帮助!

SELECT
       MAX (CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT)) AS [The Biggest Age]
     , MIN (CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT)) AS [The Smallest Age]
     , AVG (CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT)) AS [The Average Age]
FROM
      Employees

答案 1 :(得分:0)

select FirstName
     , LastName
     , BirthDate
     , GETDATE() AS [Today]
     , CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) AS [Age]
     , MIN (CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT))
FROM  Employees
GROUP BY FirstName
     , LastName
     , BirthDate
     , CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) 
HAVING CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) >=55
ORDER BY LastName ASC

答案 2 :(得分:0)

对@MAli的一些编辑回答。你不需要在GROUP BY子句中使用GETDATE(),并且按照你获得MIN的相同值进行分组只会给你相同的值。这应该是您的查询:

SELECT FirstName,LastName,BirthDate,Today,Age,
       MIN(Age) OVER ()
FROM (
    select FirstName
         , LastName
         , BirthDate
         , GETDATE() AS [Today]
         , CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) AS [Age]
    FROM  Employees
    GROUP BY FirstName
         , LastName
         , BirthDate 
    HAVING CAST (DATEDIFF (DD, BirthDate, GETDATE())/365.25 AS INT) >=55
    ) AS A
ORDER BY LastName ASC