How to find Sum of dynamically generated time attribute in sql server 2012 I have a table with two columns (TASKID and Dateadded). I am trying to find difference between timings and would like to calculate the sum of the diff (time) attribute.

 select taskid,dateAdded,CAST((dateadded -lag(dateadded) over (order by dateadded)) as time )as diff  
 from xyz where taskid=21240923 


with this statement got the difference between times but I am unable to sum the dynamically generated time column diff.



Could any body please suggest to achieve this goal?

https://www.blogger.com/blogger.g?blogID=1341056964785354138#editor/target=post;postID=5797398234800649517;onPublishedMenu=allposts;onClosedMenu=allposts;postNum=0;src=postname
Use your current query as a CTE (Common Table Expression) and select form that with aggregate functions, like:

WITH TimeDiffs AS (&lt;your query&gt;)
SELECT   taskid
       , SUM(diff)
FROM     TimeDiffs
GROUP BY taskid


(assuming you want the total per task, your question is not very clear on the details).

You could also use the existing query as a derived table:

SELECT taskid
     , SUM(diff)
FROM   (&lt;your query&gt;) AS TimeDiffs
GROUP BY taskid


which will produce the same result, though the CTE arrangement usually ends up being more readable and so easier to maintain going forward.