Get month and year from a datetime in SQL Server 2005

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

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

    That format doesn't exist. You need to do a combination of two things,

    select convert(varchar(4),getdate(),100)  + convert(varchar(4),year(getdate()))
    
    0 讨论(0)
  • 2020-12-12 16:32

    If you mean you want them back as a string, in that format;

    SELECT 
      CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) 
    FROM customers
    

    Here are the other format options

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

    How about this?

    Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
    
    0 讨论(0)
  • 2020-12-12 16:38

    Yes, you can use datename(month,intime) to get the month in text.

    0 讨论(0)
提交回复
热议问题