February 14, 2017 at 10:40 am
Hi everyone,
I have a column named "Date" with a type of "datetime" in SQL 2012.
This is an example of the data that we have in the field:
"2011-05-16 00:00:00.000"
I am doing a GROUPING with a PIVOT table. I would like to use a column por every year-month. (Example: ,201612,201701,201702, ...)
SELECT CONCAT(DATEPART(YEAR,Date), IIF(DATEPART(MM,Date) <=9, '0', '') , DATEPART(MM,Date)) as YearMonth
Finally, it works correctly, but I would like to know if this is the "correct" form.
Could I do this from another way?
Regards!
February 14, 2017 at 10:56 am
There's more than one way to do that.
in my case, the convert function would work nicely, if you include the optional code:
SELECT CONVERT(varchar(10),getdate,112) , where you replace getdate() with your datetime column.
casting it to varchar(10) strips the time out if it existed.
Lowell
February 14, 2017 at 12:16 pm
Lowell - Tuesday, February 14, 2017 10:56 AMThere's more than one way to do that.
in my case, the convert function would work nicely, if you include the optional code:
SELECT CONVERT(varchar(10),getdate,112) , where you replace getdate() with your datetime column.
casting it to varchar(10) strips the time out if it existed.
Actually, that format doesn't include time. Using a length of 6 would return year and month, and we don't need it to be variable.
SELECT CONVERT(char(6),GETDATE(), 112)
February 16, 2017 at 9:37 am
Thank you for the help!!
This form works correctly with the "Date" column
SELECT CONVERT(varchar(06),Date,112)
200902
It is the solution "200902"
And the good way is that i don't have to put the tricky part of IIF(DATEPART(MM,Date) <=9, '0', '')
to recover the "0" in the months from 01-09.
Thank you again for so fast answer
Regards!
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply