Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, In a sp I need to sum valus of a column of timespan format which saved as Varchar datatype.
(because of some reasons)
How can I convert each value to timespan and then sum that with other values
Table structure
=============================
Field ------------ Data Type
=============================
Name ------------ varchar(255)
Column A ------ varchar(50)



values of column A(hour:minute)
=============================
30:23
140:12
15:56
.
.
Posted
Updated 6-Sep-14 8:10am
v3

1 solution

You will need to parse the string, splitting hours and minutes, then add the hours and add the minutes, and divide minutes by 60 to see if you need to add any hours, and keep the remainder as minutes.
SQL
-- CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT) gives you the minutes
-- CAST(PARSENAME(REPLACE(ColumnA, ":", "."),2) as INT) gives you the hours

--@totalhours = @sumhours + @summinutes / 60
--@totalminutes = @summinutes % 60

--So the query becomes:
SELECT 
  SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),2) as INT)) + (SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT)) / 60) as totalhours,
  SUM(CAST(PARSENAME(REPLACE(ColumnA, ":", "."),1) as INT)) % 60 as remainingminutes
FROM 
  tablename
 
Share this answer
 
Comments
mit62 6-Sep-14 14:18pm    
Thanks

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