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, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
90
votes
@Evan Carroll - does this constitute hijacking the question? If you have a superior answer to the question, should it not be supplied as an answer to the question instead of pointing people to a different question?
– STLDev
@STLDeveloper how is it hijacking. The question calls for 2005? I didn't put that there. I'm not looking for 2005.. Unfortunately, the best answer here doesn't work on 2005, it's 2012-explicit. Should I downvote the 2005 answers for being archaic?
– Evan Carroll
@STLDeveloper actually, I don't care here. =) my official stance has always been to advise people to use PostgreSQL, not sure why I'm trying to help.
– Evan Carroll
It just seemed odd to me that you went back to create a new version of the question for a different version of the product, and then to answer that question, which I guess is fine.
– STLDev
20 Answers
76
votes
173
votes
12
votes
11
votes
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
SELECT
DATENAME(mm, article.Created) AS Month,
DATENAME(yyyy, article.Created) AS Year,
COUNT(*) AS Total
FROM Articles AS article
GROUP BY
DATENAME(mm, article.Created),
DATENAME(yyyy, article.Created)
ORDER BY Month, Year DESC
It produces the following ouput (example).
Month | Year | Total
January | 2009 | 2
9
votes
5
votes
4
votes
2
votes
1
votes
1
votes
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)
1
votes
---Lalmuni Demos---
create table Users
(
userid int,date_of_birth date
)
---insert values---
insert into Users values(4,'9/10/1991')
select DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years,
MONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months,
DAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,
from users
1
votes
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
0
votes
0
votes