How can I select records on the basis of their timings between specific times in SQL server -
i have sample data , part of query see fiddle. shows segment start time , end time. task sum of time segments between 6am 10pm in seconds. have filter on day how can restrict between 6am , 10 pm difficult me (may condition in case statement). second difficulty how part of segment when start time 5am , endtime 7am want display 3600 seconds part lies between 6am 10pm. if segment starts @ 9pm , finished @ 5am want 3600 seconds i.e. part before 10pm.
select userid, case when datediff(day, starttime, endtime) = 0 datediff(second, starttime, endtime) end totalsecondsfromsixamtotenpm test
here expected result, note first , second last value obtained taking these values
select datediff(second, '2015-01-14 06:00:00.000', '2015-01-14 09:25:54.000') select datediff(second, '2015-01-14 21:30:14.000', '2015-01-14 22:00:00.000') ╔════════╦══════════════════════════════╗ ║ userid ║ totalsecondsfromsixamtotenpm ║ ╠════════╬══════════════════════════════╣ ║ abc ║ 12354 ║ ║ abc ║ 3600 ║ ║ abc ║ 15150 ║ ║ abc ║ 14684 ║ ║ abc ║ 1786 ║ ║ abc ║ null ║ ╚════════╩══════════════════════════════╝
with splitteddates ( select userid, cast(starttime date) 'startdate', cast(endtime date) 'enddate', cast(starttime time) 'stime', cast(endtime time) 'etime', starttime, endtime test ), correctedtimes ( select userid, case when startdate=enddate , stime<etime , stime<'10pm' case when stime>='6am' starttime else cast(startdate datetime) + cast('6am' datetime) end end 'correctedstarttime', case when startdate=enddate , stime<etime , etime>'6am' case when etime<='10pm' endtime else cast(startdate datetime) + cast('10pm' datetime) end end 'correctedendtime' splitteddates ) select userid, datediff(second, correctedstarttime, correctedendtime) totalsecondsfromsixamtotenpm correctedtimes
result:
| userid | totalsecondsfromsixamtotenpm | |--------|------------------------------| | abc | 12354 | | abc | 3600 | | abc | 15150 | | abc | 14684 | | abc | 1786 | | abc | (null) |
edit
i added conditions stime<'10pm'
, etime>'6am'
resolve issue comments
Comments
Post a Comment