简体   繁体   中英

How to add a column vector to an existing table in SQL?

how can I add a column vector that I have created using SELECT (manipulating a column of the existing table) to that existing table?

This is my starting matrix:

name    date of Birth
Mark    15/01/1987
John    27/05/1945
Lisa    3/04/1981

I create with a SELECT and a function of the date their age:

Age
33
74
38

How can I create a new table (called table_new) in which I add the new column (Age) to the existing matrix formed by name and date of birth in SQL? As follows:

    name    date of Birth   Age
    Mark    15/01/1987   33
    John    27/05/1945   74
    Lisa    3/04/1981    38

I would recommend against storing that derived information in the table itself - ages do change over time, so maintaining the information will be tedious.

You can, instead, create a view. In Postgres, you can use date function age() , which returns an interval that represents the date difference, and then extract its year part:

create view myview(name, dob, age) as 
select
    name,
    dob,
    extract(year from age(dob))
from mytable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM