我需要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)
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)
这个怎么样?
Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )
Run Code Online (Sandbox Code Playgroud)
该格式不存在。您需要将两件事结合起来,
select convert(varchar(4),getdate(),100) + convert(varchar(4),year(getdate()))
Run Code Online (Sandbox Code Playgroud)
最好的方法是:
dateadd(month,datediff(month,0,*your_date*),0)
Run Code Online (Sandbox Code Playgroud)
它将保留您的日期时间类型
| 归档时间: |
|
| 查看次数: |
715598 次 |
| 最近记录: |