Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A possible SQL version:</p> <pre><code>WITH CTE AS( SELECT ROW_NUMBER()OVER(PARTITION BY [Name] ORDER BY [Time])As RowNum , * FROM @table T ) SELECT DiffSec=DATEDIFF(s,[Time],(SELECT [Time] FROM CTE c2 WHERE c2.[Name]=CTE.[Name] AND c2.RowNum=CTE.RowNum+1)) , [Name] , Mood , [Time] FROM CTE ORDER BY [Name],[RowNum] </code></pre> <p>Result:</p> <pre><code>DiffSec Name Mood Time 1678 Andy Happy 2012-06-11 14:06:07.000 NULL Andy Sad 2012-06-11 14:34:05.000 5228 Arthur Angry 2012-06-11 14:06:57.000 NULL Arthur Happy 2012-06-11 15:34:05.000 </code></pre> <p>Your test data:</p> <pre><code>declare @table table(name varchar(10),mood varchar(10),time datetime); insert into @table values('Andy','Happy',convert(datetime,'11.06.2012 14:06:07',104)); insert into @table values('Arthur','Angry',convert(datetime,'11.06.2012 14:06:57',104)); insert into @table values('Andy','Sad',convert(datetime,'11.06.2012 14:34:05',104)); insert into @table values('Arthur','Happy',convert(datetime,'11.06.2012 15:34:05',104)); </code></pre> <hr> <p><strong>Edit</strong> Self-Joining a <code>CTE</code> seems to be a very bad idea (<em>"<a href="http://dbaspot.com/sqlserver-programming/379487-cte-vs-temp-tables.html" rel="nofollow">If you self join the CTE it will kill you</a>"</em>). I've tested my query with 500000 records in a temporary table and cancelled the query after 30 minutes.</p> <p>Here's a much faster approach(4 seconds for all) using a sub-query (with your commented schema):</p> <pre><code>SELECT T.* ,(SELECT DATEDIFF(s,MAX(T2.Time),T.Time) FROM dbo.Temp T2 WHERE T2.HE_Id = T.HE_Id AND T2.Time &lt; T.Time ) AS DiffSec FROM dbo.Temp AS T ORDER BY HE_Id ,DiffSec </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload