【问题标题】:sql dateiff comparing age to hiredatesql dateiff 比较年龄和hiredate
【发布时间】:2020-08-12 13:40:57
【问题描述】:

第一次使用Stack Overflow,所有的课程都被扔到网上了,我的网课很糟糕。

问题很简单,我需要使用 datediff 收集刚加入公司时年龄在 35 岁或以下的员工的信息。

我的代码是这样的

Select EmployeeID, FirstName, LastName, BirthDate, HireDate,
datediff(year, BirthDate,HireDate) Age 
from Employees
where age<=35;

如果不使用“where”,它将发布人们开始时的年龄。我现在正在尝试显示我创建的年龄列,以发布小于或等于 35 岁或以下的每个人。但是,随着年龄的增长,我会遇到语法错误。显然它在sql数据库中不存在。任何帮助,将不胜感激。

【问题讨论】:

  • 这可以作为一个近似值,但它实际上不会产生公认意义上的人的“年龄”。

标签: sql date select datediff


【解决方案1】:

where 子句不能引用在select 子句中定义的别名(后者在前者之后执行)。

您需要在两个子句中重复该表达式:

select 
    e.*, 
    datediff(year, BirthDate,HireDate) Age 
from employees e
where datediff(year, BirthDate,HireDate) <= 35

或者你可以使用一个deried table(子查询或common-table-expression)——但它的效率较低,而且对于这个简单的表达式来说似乎有点过分了:

select *
from (
    select
        e.*, 
        datediff(year, BirthDate,HireDate) age 
    from employees e
) e
where age <= 35

【讨论】:

  • @ParkerSmith 。 . .惊人的很好。如果这回答了您的问题,您应该接受答案。
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多