There is a table tab1:
|creation_date | acc_num | status| |-------------------|---------------------|-------| |31.03.2021 07:43:43| 11111111111111111111| deny | |31.03.2021 07:43:43| 11111111111111111111| deny | |31.03.2021 01:43:20| 22222222222222222222| admit | |30.03.2020 21:13:21| 33333333333333333333| deny | |30.03.2021 20:28:19| 22222222222222222222| deny | |30.03.2021 20:28:19| 44444444444444444444| deny |
when I used str_to_date(), I had this uncorrect result and errors.
Query:
select year(str_to_date(creation_date, "%d.%m.%Y %h:%i:%s")) as year from tab1;
logs:
Incorrect parameter count in the call to native function 'str_to_date' Unknown column 'creation_date' in 'field list' Incorrect datetime value: '30.03.2020 21:13:21' for function str_to_date ... You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') from tab1' at line 1 Incorrect datetime value: '30.03.2020 21:13:21' for function str_to_date ... Incorrect datetime value: '30.03.2021 20:28:19' for function str_to_date
result: |year| |----| |2021| |2021| |2021| |[NULL]| |[NULL]| |[NULL]|
The question is How can I get this result:
|year| |----| |2021| |2021| |2021| |2020| |2021| |2021|
MySQL version is 8.0.23
Advertisement
Answer
If you just want the year, why not use a substring operation? After all, you’re storing the value as a string:
select substr(creation_date, 7, 4) as year
In the meantime, you should fix your table so it stores date/time values using the correct data type.