Convert String Field to Date value in a different format with an SQL select query - mysql

I have a table with a column start_date. Unfortunately, the datatype of the column is VARCHAR. Values in this column are either null or a string date in any format.
I have a requirement to extract the data from this table to a CSV file using BCP command. But while extracting, start_date value is expected to be in YYYYMMDD format in the output file.
The problem here is for some records, start_Date will be in DD/MM/YYYY format and for some others it may be in another format. For example : YYYY-MM-DD.
Is there any way so that I can convert the start_date value to the format YYYYMMDD irrespective of the actual format using the select query itself.

select convert(DATE,'13/12/2019',112) as 'AliasName'
This function will help u in fetching the data in the format of YYYYMMDD irrespective of how the format of ur input column is..This function uses 3 arguments 1.THE DATA TYPE WHICH U WANT TO CONVERT 2. YOUR INPUT COLUMN WHICH U WANT TO CONVERT 3.STYLE (style number is: Each format has its own style number for example if you give style number as 103 it will convert to dd/mm/yyyy or if 112 it will convert to YYYYMMDD ..there are many style You will find it if u search about convert function) . Hope this will help!

Hope this helps!!
select
*,
(CASE WHEN [Date] like '%/%' then TRY_CONVERT(datetime,[Date],103)
else [Date] END) as [New_DATE]
from TableName;

Related

convert any date format into YYYYmmdd in mysql

I want to convert any date format to in YYYYmmdd and want to calculate the age accordingly
user is free to insert date in any format(no restriction on format)
19990212(YYYYmmdd)
12021999(ddmmYYY)
1999-02-12(YYYY-mm-dd)
12-02-1999(dd-mm-YYY)
and son on
set #dob_c='19990212';
select if(TIMESTAMPDIFF(YEAR, date(#dob_c), CURDATE())>=21 and TIMESTAMPDIFF(YEAR, date(#dob_c), CURDATE())<100,TIMESTAMPDIFF(YEAR, date(#dob_c), CURDATE()),0)
result of the above query is correct 21, but when I change the format of the date it gives me null as a result
19990212(YYYYmmdd) >>> result is 21
12021999(ddmmYYY) >>> result is 0
1999-02-12(YYYY-mm-dd) >>> result is 21
12-02-1999(dd-mm-YYY) >>>result is 0
my query is not working for all date format,
I want to calculate the age based on any date format but it's not working
I figured out the solution to my problem. For the old record have variations in date format
So I use case to solve my problem
SET #meta_value:='1989-03-02';
SELECT
case
When LOCATE('-',#meta_value) = 0 then ifnull(DATE_FORMAT(STR_TO_DATE(#meta_value, '%Y%m%d'), '%Y%m%d'),'')
When LOCATE('-',#meta_value) > 0 then ifnull(DATE_FORMAT(STR_TO_DATE(#meta_value, '%Y-%m-%d'), '%Y%m%d'),'')
end as t
This will work for all the date formats I have. I am converting all the date formats to YYYYmmdd format. This will help me to maintain consistency. an I will update all my old record in this format only

Extract the year from the given date?

I have a date field create_at in Y-m-d format in my table. I want to extract only the year from that field.
I tried YEAR(create_at) which gives result in comma separated value.
Eg.
2017-5-12 outputs 2,017. I need without the comma.
The YEAR() will provide you integer output only.
SELECT YEAR("2017-06-15");
2017
Ref https://www.w3schools.com/sql/trymysql.asp?filename=trysql_func_mysql_year

Change Date Format from '-' to '/'

How to update or change date format "%Y-/%m-/%d" to "%Y/%m/%d" in my sql. After refreshing it goes to normal '-' format.
just use select DATE_FORMAT(yourdatecolumn, "%Y/%m/%d")
example
select DATE_FORMAT('2018-08-01', "%Y/%m/%d")
2018/08/01
From https://dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html :
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. However, it will recognize the (input) format to a date field in any of 'YYYY-MM-DD' or 'YY-MM-DD' or 'YYYY/MM/DD', 'YYYY^MM^DD' and 'YYYY#MM#DD' or even YYYYMMDD.
If you want to display a date in a different format (e.g. your chosen format of YYYY/MM/DD), then you need to change the format in the query string. Consider this example below
I have a table with 3 fields id, Date and Amount. If I run the query
SELECT id, Date, Amount FROM `dtdata` ORDER BY `dtdata`.`id` ASC
I get the output as shown:
If I want to display the date differently (i.e. your required format), I can use the following Query:
SELECT id, DATE_FORMAT(Date, "%Y/%m/%d") AS NewDate, Amount FROM `dtdata`
to get the output as

How can i do a count of two columns in mysql?

i want to do a count of two columns in mysql. One of the columns is a string but another is a date like 06/08/2017 and when i do my query i get 0 results.
SELECT count(*) FROM `castigos` WHERE inicio_normal=05/06/2017 AND cod_emplazamiento=1
I have entries of that data but its dont show me anything. Maybe the type of data in the date is wrong?
What should i do?
Add the date field to your select and group by it. Otherwise mysql extensions doesn't recognize you want to group by the date and will aggregrate all the results into 1 column. And since you are getting 0 count, you're where clause must not be working.
Your date format seems malformed. usually YYYY/MM/DD format (standard format);
or specify a format using SELECT STR_TO_DATE('17/09/2010','%d/%m/%Y');
MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
the below uses the implicit casting and default date format to convert the string date to a valid date.
SELECT inicio_normal, count(*)
FROM `castigos`
WHERE inicio_normal='2017/05/06'
AND cod_emplazamiento=1
GROUP BY inicio_normal
Otherwise its doing math and comparing that date to the number stored for the date.
Understand dates should be stored in a date datatype and when you query dates you're passing in a string that is being cast to a date datatype for comparison. So you need to use the standard format, or cast your string to a date so the db engine knows how to convert your format to a date.
Try this :
SELECT count(*) FROM `castigos` WHERE inicio_normal="05/06/2017" AND cod_emplazamiento=1 GROUP BY inicio_normal
WHERE inicio_normal=05/06/2017
If you divide 3 by 6 then by 2017 you get a very small value indeed. OTOH if you reformat this as a date (e.g. 20170605, if you gave us a European formatted date - dd/mm/yyyy) then your query will find the rows you showed us.

Convert different varchar dates to date

I'm having some troubles with converting varchar types to date types.
In SQL-server 2008 I'm having a table with different types of dates in type VARCHAR.
For example:
DDMMYYYY (05032013)<br/>
MMDDYYYY (03052013)<br/>
YYYYMMDD (20130305)<br/>
...
I have to convert these different string types to type "date" using a SQL-query.
Any suggestions how I can do this?
These are my records:
TYPE || FORMAT
____________________
DDMMYYYY||05032013
MMDDYYYY||03052013
YYYYMMDD||20130305
Try this
SELECT case
when type='DDMMYYYY' then convert(date,STUFF(STUFF('05032013',3,0,'-'),6,0,'-'),105)
when type='MMDDYYYY' then cast(substring('03052013',5,4)+'-'+substring('03052013',0,3)+'-'+substring('03052013',3,2) as date)
when type='YYYYMMDD' then cast(STUFF(STUFF('20130305',5,0,'-'),8,0,'-') as date)
end
If you can identify every row which date format is, you can convert them to date type. Otherwise i don't think that it will be completely correct. For example you can't implement logic for the following record - (03052013) can be 2013-05-03 or 2013-03-05.