2015-11-19 45 views
0

我想從特定格式的查詢中得到結果,我似乎無法找到答案。在查詢結果中格式化日期

這是我的代碼:

SELECT convert(date, TimeReported, 101) as 'Error Date', count(ErrorDetails) as 'Error Count' 

FROM ErrorLog 

where ErrorDetails like '%login failed%' 

GROUP BY Convert(date, TimeReported, 101) 

order by 'Error Date' desc 

我想要的日期結果顯示喜歡的MM/DD/YYYY

Error Date Error Count: 
11/12/2015 1 
11/05/2015 3 
03/24/2015 4 

上面的代碼給我的結果:YYYY/MM/DD

Error Date Error Count 
2015-11-12 1 
2015-11-05 3 
2015-03-24 4 
+1

我不知道數據的消費者,但我強烈建議您允許消費者在需要格式化時格式化數據,而不是在數據庫級別。 –

+0

是的,在後端格式化是相當的適得其反。 –

回答

0

試試這個:

;with cte as 
(
SELECT convert(varchar(10), TimeReported, 101) as 'Error Date', count(ErrorDetails) as 'Error Count' 
FROM ErrorLog 
where ErrorDetails like '%login failed%' 
GROUP BY convert(varchar(10), TimeReported, 101) 
) 

select * 
from cte 
order by YEAR(CONVERT(date,[Error Date])) desc, [Error Count] asc 

https://msdn.microsoft.com/en-ca/library/ms187928.aspx

+0

這會得到格式結果,但隨後按順序排列聲明,它使用月份排序而不是年份 – SHill

+0

對不起,只需將訂單更改爲TimeReported列,而不是別名「錯誤日期」。更新了答案。 – JiggsJedi

+0

這給了我:消息8127,級別16,狀態1,行9 ORDER BY子句中的「ErrorLog.TimeReported」列無效,因爲它不包含在聚合函數或GROUP BY子句中。 – SHill

0

你可以嘗試這樣的事情在您的查詢:

convert(nvarchar(10), TimeReported, 103) 
0

如果您使用的是SQL 2012或更高版本,您可以格式化數據,包括日期更豐富的方式。使用新的Format功能。 https://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx

使用此函數,您可以使用任何.NET格式說明符,單字母版本(標準)或自定義格式化程序。因此,您可以使用format(date, 'MM/dd/yyyy') as 'Error Date'而不是 convert(date, TimeReported, 101) as 'Error Date'。是的,它是區分大小寫的。如果您使用「mm」而不是「MM」,則您需要分鐘數。