计算从当前日期和DOB得出的年龄

时间:2015-11-09 20:23:39

标签: sql

我正在尝试根据当前年份和出生年份来计算用户的年龄,但我的语法中的某些内容似乎不正确,我无法发现它。

CREATE TABLE Normal_Users(

first_name varchar(20),
last_name varchar(20),
date_of_birth date,
age int = year(CURRENT_TIMESTAMP) - year(date_of_birth) 
)

为什么这不正确?

4 个答案:

答案 0 :(得分:3)

使用AS

CREATE TABLE Normal_Users(
first_name varchar(20),
last_name varchar(20),
date_of_birth date,
age int AS (year(CURRENT_TIMESTAMP) - year(date_of_birth))
);

<强> Generated columns in MySQL

  

&LT;类型&GT; [GENERATED ALWAYS] AS(&lt; expression&gt;) [   VIRTUAL | STORED] [UNIQUE [KEY]] [[PRIMARY] KEY] [NOT NULL]
  [评论]

如果您使用的是SQL Server,则 computed columns 中不需要数据类型:

CREATE TABLE Normal_Users(
    first_name varchar(20),
    last_name varchar(20),
    date_of_birth date,
    age  AS (year(CURRENT_TIMESTAMP) - year(date_of_birth))
    );

LiveDemo

修改

为了更好地计算年龄:

SELECT TIMESTAMPDIFF( YEAR, date_of_birth,  CURDATE()) AS age;

2014-12-312015-01-01的代码将返回1年,但确实为0。

答案 1 :(得分:1)

使用as关键字而不是等于:

CREATE TABLE Normal_Users(
   first_name varchar(20),
   last_name varchar(20),
   date_of_birth date,
   age int AS (year(CURRENT_TIMESTAMP) - year(date_of_birth)) 
)

答案 2 :(得分:0)

考虑到出生日期是12月并且您在1月份运行查询的情况,您需要这样的事情。

select int(
datediff(day, current_date, birth_date) / 365.25
) as yearsOld

确切的语法取决于尚未指定的数据库引擎。

答案 3 :(得分:0)

您如何在大脑中做到这一点? 您从当年减去出生年份,
如果今年已经过生日,那你就
如果可以,则表示他今年将有这个年龄(即-1岁)

多年的差异很容易。
如何比较月份和日期以了解我们之前还是之后 月* 100 +天,给出一个数字MMDD 可以很容易地比较相等或较小的值,因此在生日之后,生日那天,生日之前。

这是Sybase的原则:

declare @test char(10)
set @test='15/02/2010'

select "age" =
case when (month(convert(datetime, @test, 103))*100)+day(convert(datetime, @test, 103)) - ((month(getdate())*100)+day(getdate())) <= 0 then
    DATEDIFF(YEAR,convert(datetime, @test, 103),getdate())
else
    DATEDIFF(YEAR,convert(datetime, @test, 103),getdate())-1
end