I need to calculate the DATEDIFF
in seconds between the First record for each date with EventCode = 1
and the last record for each date with EventCode = 2
.
I have posted a sample data set for 2 days here: http://data.stackexchange.com/dba/query/515591/calculate-the-difference-between-first-event-and-last-event-for-each-date
So this is how I am getting the First Record for each Date:
Select
LogDate,
StartOfDay = MIN(LogDateTime),
EventCode
FROM (
Select
LogId,
LogDateTime,
LogDate = FORMAT(LogDateTime, 'dd-MMM-yyyy'),
DriverId,
EventCode
FROM
#MyLogs
WHERE EventCode = 1
) A
Group By
LogDate, EventCode
And this is how I am getting the Last Record for each date where EventCode = 2
Select
LogDate,
EndOfDay = MAX(LogDateTime),
EventCode
FROM (
Select
LogId,
LogDateTime,
LogDate = FORMAT(LogDateTime, 'dd-MMM-yyyy'),
DriverId,
EventCode
FROM
#MyLogs
WHERE EventCode = 2
) A
Group By
LogDate, EventCode
But how do I get the same in single result set? And I need to get the difference in seconds between the First Record for each date and Last Record for each Date.
Example of Result Set:
| Date | StartOfDay | EndOfDay | Start - End |
|-------------|-------------------------|-------------------------|-------------|
| 20-Jul-2016 | 2016-07-20 04:00:32.000 | 2016-07-20 13:05:19.000 | |
| 21-Jul-2016 | 2016-07-21 04:55:52.000 | 2016-07-21 14:49:25.000 | |
| | | | |