年龄计算查询

时间:2013-01-22 17:56:47

标签: sql sql-server

  

可能重复:
  How to calculate age in T-SQL with years, months, and days
  calculating age from sysdate and birthdate using SQL Server

在一些年龄计算的过程中。在谈到SQL时,我有点新手,但我的任务是挑选出65yrs 31 March 2013 DOB的人。到目前为止,我已经能够根据给定的SELECT ip_master.ssn, ip_master.firstname, ip_master.surname, ip_master.status, CASE WHEN DATEADD(YEAR, DATEDIFF (YEAR, dob, '2013/03/31'), dob) > '2013/03/31' THEN DATEDIFF(YEAR, dob, '2013/03/31') - 1 ELSE DATEDIFF(YEAR, dob, '2013/03/31') END AS 'Age' FROM test_db.dbo.ip_master ip_master 来计算年龄,但是我在挑出这些人时遇到了问题。我认为这是一个简单的问题,但我很难过,请参阅sql语句。有人可以指出我正确的方向。

{{1}}

4 个答案:

答案 0 :(得分:2)

在语句中附加WHERE子句:

...
WHERE dob = '1948-03-31'

答案 1 :(得分:1)

以下是否会这样做?我只是将您的查询隐藏在另一个查询中并对年龄应用了限制。

select * from
(
SELECT ip_master.ssn, ip_master.firstname, ip_master.surname, ip_master.status,

CASE WHEN DATEADD(YEAR, DATEDIFF (YEAR, dob, '2013/03/31'), dob) > '2013/03/31'
THEN DATEDIFF(YEAR, dob, '2013/03/31') - 1
ELSE DATEDIFF(YEAR, dob, '2013/03/31')
END AS 'Age'

FROM test_db.dbo.ip_master ip_master
)
where Age >= 65

答案 2 :(得分:0)

无论你做了什么都是正确的。 为了单挑,你需要一个where子句。

SELECT ip_master.ssn, ip_master.firstname, ip_master.surname, ip_master.status,

CASE WHEN DATEADD(YEAR, DATEDIFF (YEAR, dob, '2013/03/31'), dob) > '2013/03/31'
THEN DATEDIFF(YEAR, dob, '2013/03/31') - 1
ELSE DATEDIFF(YEAR, dob, '2013/03/31')
END AS 'Age'
FROM test_db.dbo.ip_master ip_master
WHERE dob = '1948-03-31'

答案 3 :(得分:0)

尝试使用以下查询...它将完美运行...

   DECLARE @CalDate datetime;
   DECLARE @CurDate datetime;
   Declare @count INT   

   SET @CalDate ='03/31/2013'
   SET @count =0
   SELECT @CurDate = DateAdd(Month, 1, @CalDate)

   SET @count = @count + datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(@CurDate) as varchar)+'-'+cast(month(@CurDate) as varchar)+'-01' as datetime))))      

   SELECT ip_master.ssn, ip_master.firstname, ip_master.surname, ip_master.status,DATEDIFF (yy, DOB, cast(@CalDate as DateTime) + @count) - (        
    CASE SIGN (MONTH (DOB) - MONTH (cast(@CalDate as DateTime) + @count))        
     WHEN 1 THEN        
      1        
     WHEN -1 THEN         
      0         
     WHEN 0 THEN         
      CASE SIGN (DAY (DOB) - DAY (@CalDate + @count))        
       WHEN 1 THEN         
        1        
       WHEN 0 THEN        
        1       
       ELSE        
        0        
      END        
    END) as AGE into #temp
    FROM test_db.dbo.ip_master ip_master 

select * from #temp where  AGE >= 65