Skip to content

Instantly share code, notes, and snippets.

@srkirkland
Created June 30, 2015 22:24
Show Gist options
  • Save srkirkland/f067a48658ef657ccec0 to your computer and use it in GitHub Desktop.
Save srkirkland/f067a48658ef657ccec0 to your computer and use it in GitHub Desktop.
select timespan between each history status
WITH a AS
(
SELECT
rt.GiftID,
rt.ActedDate,
rt.Status,
rt.Description,
ROW_NUMBER() OVER(ORDER BY rt.GiftID, rt.ActedDate) AS RN
FROM Histories rt
)
SELECT
a1.GiftID,
a2.ActedDate startdate,
a1.ActedDate enddate,
a2.Status startstatus,
a1.Status endstatus,
DATEDIFF(HOUR, a2.ActedDate, a1.ActedDate) AS Duration
FROM a a1
LEFT OUTER JOIN a a2 ON a2.RN = a1.RN - 1
WHERE
(a1.GiftID = a2.GiftID) AND (a1.Status != a2.Status)
order by a1.GiftID, startdate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment