如何创建派生属性?

时间:2018-04-19 10:02:09

标签: sql postgresql ddl calculated-columns

我需要创建一个派生属性Age,它根据Datebought属性计算元组的年龄。我发现它可以用视图制作,但我不知道在哪里放置视图。

CREATE TABLE Kids_Bike(
    BikeId ID,
    BrandName VARCHAR(max),
    ModelName VARCHAR(max),
    DateBought DATE,
    /*??????????????????????*/
    Age (SELECT datediff(day, DateBought , GETdate()) / 365.2425 ) DECIMAL,
    Color VARCHAR(max),
    StationId ID,
    TrainingWheels BIT,
    PRIMARY KEY (BikeId),
    FOREIGN KEY (StationId) REFERENCES RentingStation(StationID)
);

1 个答案:

答案 0 :(得分:0)

您将视图放在表格中:

create view v_kids_bike as
    select kb.*, extract(day from (current_date - date_bought)) / 365.2425 as age
    from kids_bike;

如果您正在使用SQL Server,则可以将create table中的计算列定义为:

Age as (SELECT datediff(day, DateBought, GETdate()) / 365.2425 ),