Get month and year from a datetime in SQL Server 2005

后端 未结 20 1449
[愿得一人]
[愿得一人] 2020-12-12 15:39

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

20条回答
  •  囚心锁ツ
    2020-12-12 16:21

    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)
    

提交回复
热议问题