从SQL Server 2005中的日期时间获取月份和年份
我需要SQL Server中日期时间的月份,如'2008年1月' . 我按月,年分组查询 . 我搜索并找到了像datepart,convert等函数,但它们似乎都没有用 . 我在这里错过了什么吗?这有功能吗?
回答(20)
有趣的是,我只是在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
将日期转换为月中的第一个允许您按单个属性分组依据和排序,并且我的体验更快 .
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)
---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
问题是关于SQL Server 2005,这里的许多答案都是针对更高版本的SQL Server .
select convert (varchar(7), getdate(),20)
--Typical output 2015-04
SQL Server 2005没有日期函数which was introduced in SQL Server 2008
2 years ago
如果你的意思是你希望它们以字符串形式返回,那就是那种格式;
Here are the other format options