2012-07-16 32 views
0

我有一個表(生產),它有一個名爲TimeSpent的列,此列的數據類型是varchar,它存儲HH:MM格式示例10:23中的數據, 14:59,11:00等。我想在sql中寫一個查詢,總結這個,只給我一個HH:MM格式的總數。 我想這樣的,但有些事情得到錯誤「轉換失敗從字符串轉換日期和/或時間。」 -SQl查詢計算HH:MM格式的總計

select CAST 
(
(SUM (datepart(hh, convert (varchar, timespent, 108))) + 
(sum(datepart(mi, convert (varchar, timespent, 108)))/60)) AS VARCHAR(2) 
) 
+ ':' + 
CAST 
(
sum(datepart(mi, convert (varchar, timespent, 108))) - 60 * (sum(datepart(mi, convert (varchar, timespent, 108)))/60) 
as VARCHAR(2)) from production 
+0

您是否將一個varchar列轉換爲具有樣式代碼HH:MM:SS的varchar列?如果timespent已經是一個var char,那麼你肯定需要在使用datepart函數之前將它轉換爲日期時間。 – Dpolehonski 2012-07-16 08:06:47

+0

是的我在做同樣的事情,TimeSpent是varchar。 – 2012-07-16 08:19:28

+0

我的查詢正在工作,只是通過減少timespent的大小爲25.謝謝 – 2012-07-16 08:40:43

回答

0

查詢工作對我來說,我剛剛更新了我的表,減少的規模TimeSpent從varchar(60)到Varchar(25)並且它是固定的。

select CAST 
(
(SUM (datepart(hh, convert (varchar, timespent, 108))) + 
(sum(datepart(mi, convert (varchar, timespent, 108)))/60)) AS VARCHAR(2) 
) 
+ ':' + 
CAST 
(
sum(datepart(mi, convert (varchar, timespent, 108))) - 60 * (sum(datepart(mi, convert (varchar, timespent, 108)))/60) 
as VARCHAR(2))from production