select datepart(mm,getdate()) --to get month value
select datename(mm,getdate()) --to get name of month
1
有趣的是,我只是在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
SELECT DATENAME(yyyy, date) AS year
FROM Income
GROUP BY DATENAME(yyyy, date)
它工作得很棒!
0
将日期转换为月中的第一个允许您按单个属性分组依据和排序,并且我的体验更快 .
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)
11
---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
20 回答
如果你的意思是你希望它们以字符串形式返回,那就是那种格式;
Here are the other format options
从SQL Server 2012开始,您可以使用:
使用:
有趣的是,我只是在SQL Server和LINQ中编写同样的查询 .
它产生以下输出(例子) .
在SQL Server 2012中,可以使用以下内容
选择FORMAT(getdate(),'MMM yyyy')
这给出了精确的“2016年6月”
这个怎么样?
那种格式不存在 . 你需要做两件事的组合,
最好的方法是:
它会保留你的日期时间类型
返回完整的月份名称, - ,全年,例如
March-2017
我有同样的问题,环顾四周后我发现了这个:
它工作得很棒!
将日期转换为月中的第一个允许您按单个属性分组依据和排序,并且我的体验更快 .
给出“2006-04”格式
是的,您可以使用
datename(month,intime)
获取文本中的月份 .问题是关于SQL Server 2005,这里的许多答案都是针对更高版本的SQL Server .
SQL Server 2005没有日期函数which was introduced in SQL Server 2008
答案:MONTH_ 1月1月9月10月12月10月9月
这很棒 .
以下工作完美!我只是用它,试一试 .