SQL: Get records created in time range for specific dates

断了今生、忘了曾经 提交于 2019-11-30 07:04:51

In Oracle we can turn dates into numbers and apply arithmetic to them in a variety of ways.

For instance sysdate-7 gives us the date seven days ago. trunc(some_date) removes the time element from a date column. And to_char(some_date, 'SSSSS') gives us its time element as the number of seconds since midnight. So 06:45:00 is 24300 seconds and 18:15:59 is 69359 seconds (please check those numbers, as they are back-of-an-envelope figgerin').

Anyway, putting that all together in a single query like this ...

select *
from your_table
where creation_date >= trunc(sysdate)-7
and to_number(to_char(creation_date, 'sssss')) between 24300 and 69359

... wil produce all the records created in the last week with a time element within core hours.

This query would return any records created in the last 7 days with the time portion of their create date between 6:45am and 7:15pm.

select * 
  from your_table
 where creation_date > sysdate - 7
   and to_char(creation_date, 'hh24:mi:ss') >= '06:45:00' 
   and to_char(creation_date, 'hh24:mi:ss') <= '19:15:00' 

Based on criteria above, this will bring back records from the last week between Sunday and Saturday in the hours of 06:45:00 and 19:15:59.

You can adjust the " - 7" and the " + 6" to different numbers if you'd like the week range to be different (for instance, if your week is Monday through Sunday).

select * 
from your_table
where creation_date >= TRUNC(SYSDATE, 'WW') - 7
and creation_date <= (TRUNC(SYSDATE, 'WW') - 7) + 6
and to_char(creation_date, 'hh24:mi:ss') >= '06:45:00' 
and to_char(creation_date, 'hh24:mi:ss') <= '19:15:00'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!