简体   繁体   中英

set a date column in sql based on a another column

So I have a SQL Table with two columns:

Col1      Col2
202205    NULL
202204    NULL
202103    NULL

Now I want to set the Date in Col2 based on the value of Col1. So the result should look like this:

Col1    Col2
202205  2022-05-01
202204  2022-04-01
202103  2021-03-01

Assuming that Col1 be text, we can try using the TO_DATE function here:

WITH yourTable AS (
    SELECT '202205' AS Col1
)

SELECT TO_DATE(Col1 || '01', 'YYYYMMDD') AS Col2  -- 2022-05-01
FROM yourTable;

MySQL:

UPDATE  test_tbl
SET Col2 = STR_TO_DATE(CONCAT(Col1,'','01') ,'%Y%m%d');

db-fiddle

create or replace table Conv(col1 number,col2 number);

insert into Conv values (202205,NULL),(202204,NULL),(202103,NULL);

select Col1,TO_DATE(Col1 || '01', 'YYYYMMDD') AS Col2 from Conv;

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