How to convert a string into date format - sql

I have the following column, date_period2 in my query which displays date in yyyy-mm format but as a string.
date_period2
201304
201305
201306
201307
How can i convert that to a DATE format so I can use it to get the working days of the specific month. So for example, 201304 would be converted to 04-2013 as a DATE instead of a string.
This is my query which is calculating an expression based on the date_period2 field and it's not working because it's a string format:
SELECT TOP 1000 [date_period2]
,[amount]
,[amount]/(SELECT 20 + COUNT(*) FROM
(SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [date_period2]), 28) AS theDate
UNION
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [date_period2]), 29)
UNION
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [date_period2]), 30) ) AS d
WHERE DATEPART(DAY, [date_period2]) > 28 AND DATEDIFF(DAY, 0, [date_period2]) % 7 < 5) AS [Weekly Charge]
FROM [database].[dbo].[table]
The issue is the amount is being divided by 20 and not by the working days for the month-year.
Example:
date_period2 amount charge average (amount/total working days of the month)
201304 1750359.95 87517.9975
So according to the result above the charge average is supposed to be 1750359.95/22, but instead it is being divided by 20 giving it the wrong output.
How can I either edit the query or convert the date to ensure the output is done correctly?

Just put the string in an unambiguous date format like yyyy-mm-dd:
SELECT
CONVERT(DATETIME,
SUBSTRING(date_period2,1,4) + '-'
+ SUBSTRING(date_period2,5,2) + '-01')
That will convert 201304 into 2013-04-01 which will convert directly to a DateTime.
EDIT
Since your source column is actually an integer column, a cleaner method is:
select CONVERT(DATETIME,CONVERT(CHAR(6),date_period2)+'01')
that will convert 201304 to "20130401" whihc is still unambiguous to the datetime parser.

You can convert date_period2 to a datetime data type with following logic.
Please change as per your need.
declare #i int
select #i = CONCAT('201305','01')
select CONVERT (datetime,convert(char(8),#i))
In CONCAT('201305','01') '01' will be constant, only '201305' will change.

201404 can converted into 04-2014
declare #x VARCHAR(20)
SET #x = convert(varchar(7), getdate(), 126)
select SUBSTRING(#x,6,CHARINDEX('-',#x)) +'-'+SUBSTRING(#x,0,CHARINDEX('-',#x))

Related

Date conversion for YY-Monthtext to MM/DD/YYYY

Receive date as "19-May" and need to convert it as '05/01/2019', "19-June" to '06/01/2019'.
I have tried various date conversion but it didn't work.
You can try this. Storing date in this format is not a good/suggestion you should use the proper data type which are meant and available for.
You should update the values with proper date time value and then change the data type also. It will save your time & you do not need these conversions every time.
Select Try_Cast('19-May 2019' as Datetime)
OR
Select Try_Cast('19-May' + '2019' as Datetime)
To get the first date of month you can try the below query.
SELECT DATEADD(month, DATEDIFF(month, 0, Try_Cast('19-May 2019' as Datetime)), 0) AS StartOfMonth
Edit
To get the first date of month as per the given data in string, you can use the below query.
declare #dateinStr varchar(20) = '19-May'
Select try_cast('01-' + Replace(#dateinStr, LEFT(#dateinStr, 3), '') + LEFT(#dateinStr, 2) as Datetime) as Date
Here is the demo.
I suppose the months will be 3 chars only, if so then
Select s,
try_Cast(concat(right(s, 3), ' 2019') as Datetime)
from
(
values
('19-May'),
('19-Jun')
) t(s);
If the months is really comes like "June" & "August" then
select s,
try_cast(concat(substring(s, charindex('-',s)+1, 3), ' 2019') as date)
from
(
values
('19-May'),
('19-June'),
('15-August')
) t(s);
If you need to format it as mm/dd/yyyy then use 101 style.
You can do :
SELECT DATEADD(DAY, 1, EOMONTH(CONVERT(DATE, Dates + '-2019'), -1))
FROM ( VALUES ('19-May'), ('19-June')
) t(Dates);

SQL Server date time convert

I have a field in my database table called Month which holds its values as an INT it has the values 1 to 12 - I would like a way to convert 1 to read 1-11-2016 00:00:00 ie as a datetime field, 2 to read 1-12-2016 00:00:00, 3 to read 1-1-2017 00:00:00 - how can I convert a value like this? I am ok with doing case to switch but the convert/cast is confusing me...
You need to define a startdate (either by parameter or in a CTE), then just use dateadd()
#StartDate = '2016-10-01 00:00:00'
select dateadd(mm, t1.month, #StartDate) as NewMonth
from MyTable t1
Another response is
SELECT CONVERT(DATE, '2016-' + CAST(id AS VARCHAR(2)) + '-01') AS myDate
FROM T1
But y prefer JohmHC answer !!

Convert Decimal or Varchar into Date

I have 2 fields.
Birth= Datatype Decimal(12,4) & Date = Datatype Date
Birth Date
19650101 2015-07-09
how do i get a result that looks like this
i want the result to be like this
Birth Date
1965-01-01 2015-07-09
where the Birth is a Date datatype and not a decimal (12,4)
To convert the number 19650101 to a date use
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)
To get the number of years (to one decimal) you could do:
ROUND(
DATEDIFF(day,
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
[Date])/365.25
,1)
Which won't be exact but should be close enough to tenths of a year.
You can use this:
-- Create demo data
CREATE TABLE #dates(birth int, date date)
INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')
-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date,
DATEDIFF(year,
CONVERT(date,CONVERT(nvarchar(max),birth),112),
date
) as years
FROM #dates
-- Cleanup
DROP TABLE #dates
This depends on the exact format you provides (19650101).
Here is one way to do this conversion.
cast(cast(FLOOR(birth) as CHAR(8)) as DATE)
I think you don't need to round. Just convert your decimal value and put "-" like below : )
select left(birth,4) +'-' +
substring(convert(nvarchar,birth),5,2)+'-'+
substring(convert(nvarchar,birth),7,2)

SQL Output to get only last 7 days output while using convert on date

I am using the below SQL Query to get the data from a table for the last 7 days.
SELECT *
FROM emp
WHERE date >= (SELECT CONVERT (VARCHAR(10), Getdate() - 6, 101))
AND date <= (SELECT CONVERT (VARCHAR(10), Getdate(), 101))
ORDER BY date
The data in the table is also holding the last year data.
Problem is I am getting the output with Date column as
10/11/2013
10/12/2012
10/12/2013
10/13/2012
10/13/2013
10/14/2012
10/14/2013
10/15/2012
10/15/2013
10/16/2012
10/16/2013
10/17/2012
10/17/2013
I don't want the output of 2012 year. Please suggest on how to change the query to get the data for the last 7 days of this year.
Instead of converting a date to a varchar and comparing a varchar against a varchar. Convert the varchar to a datetime and then compare that way.
SELECT
*
FROM
emp
WHERE
convert(datetime, date, 101) BETWEEN (Getdate() - 6) AND Getdate()
ORDER BY
date
Why convert to varchar when processing dates? Try this instead:
DECLARE #Now DATETIME = GETDATE();
DECLARE #7DaysAgo DATETIME = DATEADD(day,-7,#Now);
SELECT *
FROM emp
WHERE date BETWEEN #7DaysAgo AND #Now
ORDER BY date
Use this, simply.
Select columnname
from tablename
WHERE datecolumn> dateadd(day,-7,GETDATE())

Month year back (SQL)

I m trying to dig more in the SQL query , I'm with it.
Yearmo Back_1_month
------- ------------
201202 201201 Where 201202 is Feb 2012 , 201201 is Jan 2012
201201 201112
201204 201203
201212 201211
I m confused , how can make it for 201201.
Assuming that yearmo is an int:
DECLARE #Yearmo INT
SET #Yearmo = 201201
-- First, convert yearmo to a varchar.
-- Next, add a "day" portion to the varchar.
-- Then, convert to a date.
-- Then, subtract a month.
-- Finally, convert back to your original format using char(6).
SELECT CONVERT(
CHAR(6),
(DATEADD(MONTH, -1, CAST(CAST(#YearMo AS VARCHAR) + '01' AS DATETIME))),
112
)
This works in one single sql query :
SELECT CONVERT(VARCHAR(6), DATEADD(month, -1 , convert(datetime, CAST ( 201201 AS VARCHAR(8)) + '01', 112) ) , 112)
To substract a month, you can use DATEADD like this
SELECT DATEADD(month, -1, yearmo)
But then you will need to format your date and you might need to cast yearmo as a datetime if it's not.
Try this:
SELECT yearmo,
LEFT(CONVERT(CHAR(8), DATEADD(month, -1, CONVERT(datetime, yearmo + '01')), 112), 6)
FROM <YOUR_TABLE>
SQL Fiddle
You can create a Stored Procedure with argument as yearmo and then save substring(yr) and substring(mo) in two variables and then see, if substring(mo) is 01 then decrement substring(yr) after casting and change substring(mo) to 12 and then append both substring and return.