简体   繁体   中英

Add date column that based upon other date column SQL BQ

I have a column of dates in my table (referred as org_day). I try to add a new column that represent the day after, that is day_after = org_day + day (or 24 hours) (for all rows of org_day)

From what I've read, the DATE_ADD function of SQL does not work on the entire column, so trying to do something like: DATE_ADD (org_day, INTERVAL 24 HOUR) or DATE_ADD (DATE org_day, INTERVAL 24 HOUR) do not work. The usual examples that do work look like: DATE_ADD (DATE '2019-12-22', INTERVAL 1 day), But I want to perform this operation on the entire column, not on a constant date. Appreciate any help.

To update the entire column, you need to set everything on that column. Try this, hope it solved ur problem...

UPDATE table_name SET column_name = DATE_ADD(var, interval);

You can try this:

CREATE OR REPLACE TABLE
  mydataset.mytable AS
SELECT
  org_day,
  DATE_ADD(org_day, INTERVAL 1 day) day_after
FROM
  mydataset.mytable;

This above statement will modify the the existing table by adding a new column, without deleting exiting data.

I would suggest using a view:

create view v_t as
    select t.*, date_add(org_day, interval 1 day) as day_after
    from t;

If you always want the new column to be in synch with existing column, then a view ensures that the data is consistent. The value is calculated when you query the data .

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