从 SQL Server 2005 中的日期时间获取月份和年份
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get month and year from a datetime in SQL Server 2005
提问by Malik Daud Ahmad Khokhar
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, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
我需要 SQL Server 中日期时间的月份+年份,例如“2008 年 1 月”。我按月、年对查询进行分组。我已经搜索并找到了诸如 datepart、convert 等函数,但似乎没有一个对此有用。我在这里错过了什么吗?有这个功能吗?
采纳答案by robsoft
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
回答by HS.
select
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
回答by CrimsonKing
Beginning with SQL Server 2012, you can use:
从 SQL Server 2012 开始,您可以使用:
SELECT FORMAT(@date, 'yyyyMM')
回答by don
Use:
用:
select datepart(mm,getdate()) --to get month value
select datename(mm,getdate()) --to get name of month
回答by Mike Geise
Funny, I was just playing around writing this same query out in SQL Server and then LINQ.
有趣的是,我只是在 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
It produces the following ouput (example).
它产生以下输出(示例)。
Month | Year | Total
January | 2009 | 2
回答by webbuilder
In SQL server 2012, below can be used
在 SQL Server 2012 中,可以使用下面的
select FORMAT(getdate(), 'MMM yyyy')
选择格式(getdate(),'MMM yyyy')
This gives exact "Jun 2016"
这给出了确切的“Jun 2016”
回答by GordyII
How about this?
这个怎么样?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
回答by SQLMenace
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()))
回答by SQLMenace
( Month(Created) + ',' + Year(Created) ) AS Date
回答by cyber cyber1621
the best way to do that is with :
最好的方法是:
dateadd(month,datediff(month,0,*your_date*),0)
it will keep your datetime type
它将保留您的日期时间类型