0
DECLARE @age DATETIME
SET @age = (GETDATE() - emp.Birthdate)

SELECT 
    emp.BusinessEntityID, emp.BirthDate, @age
FROM 
    HumanResources.Employee AS emp
WHERE 
    emp.OrganizationLevel > = 3 
    AND ((GETDATE() - emp.Birthdate) BETWEEN '1930-01-01 00:00:00.000' AND '1940-01-01 00:00:00.000')

正如您所看到的,这行不通,我希望显示 30-40 岁的人的年龄以及他们的 id、bday 和年龄。声明@age 是我的问题。我尝试使用substring(getdate...), 2, 2),但它似乎不起作用。有任何想法吗?谢谢

4

5 回答 5

1

在您将值设置为的那一刻@age

SET @age = (GETDATE() - emp.Birthdate)

没有emp

您可以简单地执行以下查询:

SELECT emp.BusinessEntityID, emp.BirthDate, (GETDATE() - emp.Birthdate) AS Age
FROM HumanResources.Employee AS emp
WHERE emp.OrganizationLevel > = 3 AND
      (GETDATE() - emp.Birthdate) BETWEEN '1930-01-01 00:00:00.000' AND '1940-01-01 00:00:00.000')
于 2015-11-26T05:36:43.623 回答
0

我认为您正在尝试让员工年龄在 30 到 40 岁之间,您可以简单地使用DateDiffFunction 来执行此操作,如下查询:

SELECT BusinessEntityID,BirthDate,DATEDIFF(YEAR,BirthDate,GETDATE()) AS Age 
FROM HumanResources.Employee 
WHERE DATEDIFF(YEAR,BirthDate,GETDATE()) BETWEEN 30 AND 40 
ORDER BY Age ASC    
于 2015-11-26T05:46:10.027 回答
0

无需在查询中使用变量。您可以简单地执行以下操作:

SELECT t.BusinessEntityID, t.BirthDate, t.Age
FROM
(SELECT emp.BusinessEntityID, emp.BirthDate, CAST(datediff(DAY, emp.Birthdate, GETDATE()) / (365.23076923074) as int) as 'Age'
FROM HumanResources.Employee AS emp
WHERE emp.OrganizationLevel > = 3) t
WHERE t.Age >= 30 and t.Age <=40
于 2015-11-26T05:46:13.877 回答
0

首先,您不能设置具有多个值的标量变量。其次,为此您根本不需要变量。你可以简单地这样做:

SELECT BusinessEntityID, BirthDate, DATEDIFF(Year, BirthDate, GETDATE()) As Age
FROM HumanResources.Employee 
WHERE OrganizationLevel > = 3 
AND DATEDIFF(Year, BirthDate, GETDATE()) BETWEEN 30 AND 40

注意:这不会给出确切的年龄。要获得确切的年龄,您可以使用这篇文章中的答案。我认为最好的答案是dotjoe这个答案

于 2015-11-26T05:42:09.080 回答
0

您可以使用Datediff函数来查找 2 个日期之间的确切差异

SELECT 
     datediff(yyyy,GETDATE(),date)
FROM 
     [PRGX_AS_SandBox].[dbo].[Test_SO]
于 2015-11-26T05:38:28.997 回答