Click here to Skip to main content
15,917,568 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have a table(production) which is having a column with name TimeSpent, the datatype of this column is varchar and it stores data in HH:MM format example 10:23,14:59,11:00 etc.I want to write a query in sql which will sum this and give me a total in HH:MM Format only. I tried some thing like this but getting error 'Conversion failed when converting date and/or time from character string.':-

SQL
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
Posted
Comments
graciax8 16-Jul-12 4:34am    
why did you assign the column as varchar if you'll calculate it later?
Dharmenrda Kumar Singh 16-Jul-12 5:38am    
Becoz to maintain the format i used varchar, Previously it is not required and we just want data to display in HH:MM format and after that the requirement changed and asked to me to populate total also of the duration.

1 solution

Query worked for me, I had just updated my table and decreased the size of TimeSpent to Varchar(25) from varchar(60) and it is fixed.
SQL
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
 
Share this answer
 
Comments
Sandeep Mewara 16-Jul-12 8:09am    
Comment from OP:

Dharmenrda Kumar ,

For the same HH:MM calculation. I have written very big lengthy coding (like story),using if condition and for loop.Thanks a lot for your query.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900