问题
I have a set of records that were created last week, and from those I want to retrieve only those that were created between 6h45 and 19h15. I have a column creation_date
that I can use.
How can I do this in sql?
回答1:
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.
回答2:
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'
回答3:
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'
来源:https://stackoverflow.com/questions/9568787/sql-get-records-created-in-time-range-for-specific-dates