@name('potentialHomeOvernightStayIntervals')
select
    c.sessionId as sessionId,
    c.driverKey as driverKey,
    c.startedAt as startedAt,
    c.endedAt as endedAt,
    c.durationSeconds as durationSeconds,
    sum(
        case
            when u.startedAtEpochSecond <= c.startedAtEpochSecond and u.endedAtEpochSecond >= c.endedAtEpochSecond
                then c.durationSeconds
            when u.startedAtEpochSecond <= c.startedAtEpochSecond
                then u.endedAtEpochSecond - c.startedAtEpochSecond
            when u.endedAtEpochSecond >= c.endedAtEpochSecond
                then c.endedAtEpochSecond - u.startedAtEpochSecond
            else u.endedAtEpochSecond - u.startedAtEpochSecond
        end
    ) as cardAbsentDurationSeconds,
    (sum(
        case
            when u.startedAtEpochSecond <= c.startedAtEpochSecond and u.endedAtEpochSecond >= c.endedAtEpochSecond
                then c.durationSeconds
            when u.startedAtEpochSecond <= c.startedAtEpochSecond
                then u.endedAtEpochSecond - c.startedAtEpochSecond
            when u.endedAtEpochSecond >= c.endedAtEpochSecond
                then c.endedAtEpochSecond - u.startedAtEpochSecond
            else u.endedAtEpochSecond - u.startedAtEpochSecond
        end
    ) * 100.0d) / c.durationSeconds as cardAbsentCoveragePercent,
    c.previousDrivingSourceIntervalId as previousDrivingSourceIntervalId,
    c.nextDrivingSourceIntervalId as nextDrivingSourceIntervalId,
    c.previousRegistrationKey as previousRegistrationKey,
    c.nextRegistrationKey as nextRegistrationKey,
    c.previousVehicleKey as previousVehicleKey,
    c.nextVehicleKey as nextVehicleKey
from TachographDrivingInterruptionVehicleChangeIntervalInputEvent as c unidirectional,
     TachographVuCardAbsentIntervalInputEvent#keepall as u
where u.driverKey = c.driverKey
  and u.startedAtEpochSecond < c.endedAtEpochSecond
  and u.endedAtEpochSecond > c.startedAtEpochSecond
group by
    c.sessionId,
    c.driverKey,
    c.startedAt,
    c.endedAt,
    c.startedAtEpochSecond,
    c.endedAtEpochSecond,
    c.durationSeconds,
    c.previousDrivingSourceIntervalId,
    c.nextDrivingSourceIntervalId,
    c.previousRegistrationKey,
    c.nextRegistrationKey,
    c.previousVehicleKey,
    c.nextVehicleKey
having sum(
    case
        when u.startedAtEpochSecond <= c.startedAtEpochSecond and u.endedAtEpochSecond >= c.endedAtEpochSecond
            then c.durationSeconds
        when u.startedAtEpochSecond <= c.startedAtEpochSecond
            then u.endedAtEpochSecond - c.startedAtEpochSecond
        when u.endedAtEpochSecond >= c.endedAtEpochSecond
            then c.endedAtEpochSecond - u.startedAtEpochSecond
        else u.endedAtEpochSecond - u.startedAtEpochSecond
    end
) * 100L >= c.durationSeconds * 95L;
