What Oracle SQL syntax do I need to find transactions that occurred during time intervals of a day for a period of a year

oracleplsql

I am looking at a transactional-level table for which I need to extract all transactions which occurred between certain hours (between 15:00 and 23:59) of a day for the past year. How can I do this using Oracle SQL syntax?

Best Answer

Simply add a WHERE-condition like this:

WHERE datecol BETWEEN DATE '2014-01-01' AND DATE '2014-12-31' 
  AND EXTRACT(HOUR FROM CAST(datecol AS TIMESTAMP(0))) BETWEEN 15 AND 23

To dynamically define the previous year:

WHERE datecol >= ADD_MONTHS(TRUNC(CURRENT_DATE, 'year'), -12) -- jan 1st previous year
  AND datecol < TRUNC(CURRENT_DATE, 'year')                   -- jan 1st current year
  AND EXTRACT(HOUR FROM CAST(datecol AS TIMESTAMP(0))) BETWEEN 15 AND 23