I need the month+year from the datetime in SQL Server like \'Jan 2008\'. I\'m grouping the query by month, year. I\'ve searched and found functions like datepart, convert, e
Beginning with SQL Server 2012, you can use:
SELECT FORMAT(@date, 'yyyyMM')
The question is about SQL Server 2005, many of the answers here are for later version SQL Server.
select convert (varchar(7), getdate(),20)
--Typical output 2015-04
SQL Server 2005 does not have date function which was introduced in SQL Server 2008
In SQL server 2012, below can be used
select FORMAT(getdate(), 'MMM yyyy')
This gives exact "Jun 2016"
I had the same problem and after looking around I found this:
SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)
It's working great!
Converting the date to the first of the month allows you to Group By and Order By a single attribute, and it's faster in my experience.
declare @mytable table(mydate datetime)
declare @date datetime
set @date = '19000101'
while @date < getdate() begin
insert into @mytable values(@date)
set @date = dateadd(day,1,@date)
end
select count(*) total_records from @mytable
select dateadd(month,datediff(month,0,mydate),0) first_of_the_month, count(*) cnt
from @mytable
group by dateadd(month,datediff(month,0,mydate),0)
The following works perfectly! I just used it, try it out.
date_format(date,'%Y-%c')