从SQL Server 2005中的日期时间获取月份和年份

Mal*_*har 82 sql sql-server

我需要SQL Server中日期时间的月份+年份,如'2008年1月'.我按月,年分组查询.我搜索并找到了像datepart,convert等函数,但它们似乎都没有用.我在这里错过了什么吗?这有功能吗?

HS.*_*HS. 169

select 
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
Run Code Online (Sandbox Code Playgroud)

  • @ jp2code**month**和**year**基本上是这里定义的常量:http://msdn.microsoft.com/en-us/library/ms174420.aspx.TSQL通过阅读它们来理解它们,就像读取它们一样:) (4认同)

rob*_*oft 73

如果你的意思是你希望它们以字符串形式返回,那就是那种格式;

SELECT 
  CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) 
FROM customers
Run Code Online (Sandbox Code Playgroud)

以下是其他格式选项


Cri*_*ing 40

从SQL Server 2012开始,您可以使用:

SELECT FORMAT(@date, 'yyyyMM')
Run Code Online (Sandbox Code Playgroud)


小智 12

使用:

select datepart(mm,getdate())  --to get month value
select datename(mm,getdate())  --to get name of month
Run Code Online (Sandbox Code Playgroud)


Mik*_*ise 11

有趣的是,我只是在SQL Server和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
Run Code Online (Sandbox Code Playgroud)

它产生以下输出(例子).

Month | Year | Total

January | 2009 | 2
Run Code Online (Sandbox Code Playgroud)


小智 9

在SQL Server 2012中,可以使用以下内容

选择FORMAT(getdate(),'MMM yyyy')

这给出了精确的"2016年6月"


Gor*_*yII 6

这个怎么样?

Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
Run Code Online (Sandbox Code Playgroud)


SQL*_*ace 5

该格式不存在。您需要将两件事结合起来,

select convert(varchar(4),getdate(),100)  + convert(varchar(4),year(getdate()))
Run Code Online (Sandbox Code Playgroud)


小智 5

( Month(Created) + ',' + Year(Created) ) AS Date
Run Code Online (Sandbox Code Playgroud)


cyb*_*621 5

最好的方法是:

dateadd(month,datediff(month,0,*your_date*),0)
Run Code Online (Sandbox Code Playgroud)

它将保留您的日期时间类型