问题
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?
回答1:
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.
回答2:
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.
回答3:
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))
来源:https://stackoverflow.com/questions/23365671/how-to-convert-a-string-into-date-format