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

时间:2020-03-05 18:48:08  来源:igfitidea点击:

我需要像'Jan 2008'这样的SQL Server中日期时间的月份+年。我按月,年对查询进行分组。我已经搜索并找到了datepart,convert等功能,但是似乎没有一个有用的功能。我在这里想念什么吗?有这个功能吗?

解决方案

回答

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

select convert(varchar(4),getdate(),100)  + convert(varchar(4),year(getdate()))

回答

如果我们想让它们以字符串形式返回,则应采用这种格式;

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

这是其他格式选项

回答

select 
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)

回答

( Month(Created) + ',' + Year(Created) ) AS Date

回答

有趣的是,我只是想在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

它产生以下输出(示例)。

Month | Year | Total

January | 2009 | 2

回答

我遇到了同样的问题,环顾四周后发现:

SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)

效果很好!

回答

这个怎么样?

Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )

回答

是的,我们可以使用datename(month,intime)以文本形式获取月份。

回答

使用:

select datepart(mm,getdate())  --to get month value
select datename(mm,getdate())  --to get name of month