我有以下sql查询,它以Month格式返回DateTime格式的信息,如12月或Novermber:
SELECT COUNT(DISTINCT dbo.UserQuiz.QuizID) AS [Total Number of Taken Quizzes], dbo.Divisions.DivisionName, DATENAME(Month, dbo.UserQuiz.DateTimeComplete)
AS Month
FROM dbo.UserQuiz INNER JOIN
dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID INNER JOIN
dbo.employee ON dbo.UserQuiz.Username = dbo.employee.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode
GROUP BY dbo.Divisions.DivisionName, DATENAME(Month, dbo.UserQuiz.DateTimeComplete)
我想以任何格式获取日期,例如:mm-dd-yyyy。怎么做?
答案 0 :(得分:1)
select cast(convert(varchar, datefield, 112) as datetime)
这用于返回datetime,如果你想要一个字符串 - 只用正确的格式编号转换而不是112
对于服务器版本2008+,您可以在GROUP BY
子句构造中使用更简单快速的方法,如
CAST(dbo.UserQuiz.DateTimeComplete as DATE)
答案 1 :(得分:1)
SELECT COUNT(DISTINCT dbo.UserQuiz.QuizID) AS [Total Number of Taken Quizzes], dbo.Divisions.DivisionName, convert(varchar,dbo.UserQuiz.DateTimeComplete,110 )
AS Month
FROM dbo.UserQuiz INNER JOIN
dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID INNER JOIN
dbo.employee ON dbo.UserQuiz.Username = dbo.employee.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode
GROUP BY dbo.Divisions.DivisionName,convert(varchar,dbo.UserQuiz.DateTimeComplete,110)
答案 2 :(得分:0)
我可能只将日期作为日期时间值返回,并将格式化作业保留给客户端应用程序。您可以重置日期时间的时间和日期部分,如下所示:
DATEADD(MONTH, DATEDIFF(MONTH, 0, your_datetime_value), 0)
上述表达式返回相应月份的第一个月的午夜,例如对于2011-12-26 16:49:53.487
,它会产生2011-12-01 00:00:00.000
。