Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try this, instead of <code>#tbl</code> put your table name:</p> <pre><code>DROP TABLE #tbl CREATE TABLE #tbl([Date] DATETIME, [Status] INT) INSERT #tbl VALUES ('2012-09-01 00:01:00.000', 2), ('2012-09-01 04:17:00.000', 4), ('2012-09-01 04:34:00.000', 4), ('2012-09-01 04:35:00.000', 4), ('2012-09-01 04:35:48.000', 4), ('2012-09-01 04:35:51.000', 1), ('2012-09-01 17:28:25.000', 2), ('2012-09-01 23:58:00.000', 4), ('2012-09-01 23:59:00.000', 1), -- for 2012-09-05 there are no statuses 1 or 2 --('2012-09-05 00:01:00.000', 2), ('2012-09-05 04:17:00.000', 4), ('2012-09-05 04:34:00.000', 4), ('2012-09-05 04:35:00.000', 4), ('2012-09-05 04:35:48.000', 4), ('2012-09-05 04:35:51.000', 4), ('2012-09-05 17:28:25.000', 4), ('2012-09-05 23:58:00.000', 4) --('2012-09-05 23:59:00.000', 1) ;WITH tbl AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY [Date]) id FROM #tbl ), b AS ( SELECT MIN([Date]) MinDate, MAX([Date]) MaxDate, CAST([Date] AS DATE) dateWithoutTime FROM tbl GROUP BY CAST([Date] AS DATE) ), a AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY [Date]) num FROM tbl LEFT JOIN b ON b.MaxDate = [Date] OR b.MinDate = [Date] WHERE [Status] IN (2, 1) OR [Date] = CASE WHEN NOT EXISTS (SELECT 1 FROM #tbl c WHERE c.Status = 2 AND CAST(c.[Date] AS DATE) = b.dateWithoutTime) THEN b.MinDate END OR [Date] = CASE WHEN NOT EXISTS (SELECT 1 FROM #tbl c WHERE c.Status = 1 AND CAST(c.[Date] AS DATE) = b.dateWithoutTime) THEN b.MaxDate END ) SELECT tbl.Date, tbl.Status, CASE WHEN a2.num % 2 = 0 THEN DATEDIFF(MINUTE, a1.Date, a2.Date) END Diff FROM tbl LEFT JOIN a a2 ON tbl.id = a2.id LEFT JOIN a a1 ON a2.num = a1.num + 1 ORDER BY [Date] </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.
 

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