There is a column in a table with dates called ‘date_activated’. I would like to add a column and use the information from the ‘date_activated’ to produce a datetime format that sets to the first day of the year.
For example:
id | date_activated | datetime |
---|---|---|
1. | 2016-05-12 | 2016-01-01 0:00:00 |
2. | 2019-05-16 | 2019-01-01 0:00:00 |
2
Answers
Here is the query:
and matching output:
If you want to alter the table you do that, then update the column with the
cast
expression.First,
ALTER
your table to add your additional column:Note: your newly created column named
datetime
is a Keyword in MySQL. It is not advised to name things after Keywords or Reserved Words.Next,
UPDATE
your column using anINNER JOIN
to self-join your tables in order to get the year from thedate_activated
column:Using
YEAR()
, you can extract the year fromdate_activated
thenCONCAT
it with'-01-01 00:00:00'
to fit your newtimestamp
columns format.If you’re just trying to add it to your
SELECT
statement without altering or updating your table:Input:
Output:
db<>fiddle here.