在SQL中使用两次相同的输出时,如何避免重复函数?

时间:2017-08-02 09:58:35

标签: sql-server datediff

我正在玩 Microsoft SQL Server 以熟悉该软件并学习SQL。我正在使用一个示例数据库,其中包含有关公司员工的信息。

以下是我目前正在使用的代码:

SELECT [LoginID]
      ,[OrganizationLevel]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[HireDate]
      ,[VacationHours]
      ,[SickLeaveHours]
      ,DateDiff(Year, BirthDate, GetDate()) AS 'Age'
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  WHERE MaritalStatus = 'M' AND (DateDiff(Year, BirthDate, GetDate()) > 40)
  ORDER BY Gender, Age ASC;

正如您所看到的,我只想展示截至今日已超过40岁的已婚员工,但也要显示他们在“年龄”中的年龄。列。

我尝试了以下内容:

WHERE MaritalStatus = 'M' AND ((DateDiff(Year, BirthDate, GetDate())) AS 'Age') > 40

为了避免两次使用DATEDIFF()函数,但不成功。

我猜这与

有关
DateDiff(Year, BirthDate, GetDate()) AS 'Age'

SELECT之外,但目前我找不到另一种解决方案。

提前感谢能够启发我的人。

3 个答案:

答案 0 :(得分:1)

您可以使用几个APPLY来计算实际年龄并减少重复次数,但请注意,系统应该已经优化了这一点。

SELECT [LoginID]
      ,[OrganizationLevel]
      ,[JobTitle]
      ,[BirthDate]
      ,[MaritalStatus]
      ,[Gender]
      ,[HireDate]
      ,[VacationHours]
      ,[SickLeaveHours]
      ,Age
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  CROSS APPLY (SELECT DATEDIFF(year,BurthDate,GetDate()) as PotentialAge) a
  CROSS APPLY (SELECT CASE WHEN DATEADD(year,PotentialAge,BirthDate) > GetDate() 
               THEN PotentialAge - 1 ELSE PotentialAge END as Age) b
  WHERE MaritalStatus = 'M' AND Age > 40
  ORDER BY Gender, Age ASC;

正如评论中所指出的,我们必须做更多工作来生成实际年龄,因为DATEDIFF计算过渡

答案 1 :(得分:0)

AS语句只能在Select语句中。

SELECT [LoginID]
  ,[OrganizationLevel]
  ,[JobTitle]
  ,[BirthDate]
  ,[MaritalStatus]
  ,[Gender]
  ,[HireDate]
  ,[VacationHours]
  ,[SickLeaveHours]
  ,DateDiff(Year, BirthDate, GetDate()) AS 'Age'
  FROM [AdventureWorks2014].[HumanResources].[Employee]
  WHERE MaritalStatus = 'M' AND (DateDiff(Year, BirthDate, GetDate()) > 40)
  ORDER BY Gender, DateDiff(Year, BirthDate, GetDate()) ASC;

每次要使用它时都必须重复此功能... 我想这就是你想要做的。正确吗?

答案 2 :(得分:-1)

我认为您的架构信息不正确。 尝试删除[AdventureWorks2014]。[HumanResources]并仅放置[Employee]

  SELECT [LoginID]
  ,[OrganizationLevel]
  ,[JobTitle]
  ,[BirthDate]
  ,[MaritalStatus]
  ,[Gender]
  ,[HireDate]
  ,[VacationHours]
  ,[SickLeaveHours]
  ,DateDiff(Year, BirthDate, GetDate()) AS 'Age'
 FROM Employee]
 WHERE MaritalStatus = 'M' AND (DateDiff(Year, BirthDate, GetDate()) > 40)
 ORDER BY Gender, Age ASC;