Get month and year from a datetime in SQL Server 2005

后端 未结 20 1450
[愿得一人]
[愿得一人] 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:18

    Beginning with SQL Server 2012, you can use:

    SELECT FORMAT(@date, 'yyyyMM')
    
    0 讨论(0)
  • 2020-12-12 16:18

    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 讨论(0)
  • 2020-12-12 16:20

    In SQL server 2012, below can be used

    select FORMAT(getdate(), 'MMM yyyy')

    This gives exact "Jun 2016"

    0 讨论(0)
  • 2020-12-12 16:21

    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!

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-12 16:21

    The following works perfectly! I just used it, try it out.

    date_format(date,'%Y-%c')
    
    0 讨论(0)
提交回复
热议问题