0

i have some question regarding about get data from database which need to fetch from past year ( dynamic , not hard-coded )

Table: BookingTable

bookingID   userID     Timebooked 
1             0003    10-May-2016
2             0001    10-May-2018
3             0001    10-Apr-2017
4             0001    10-Apr-2017
5             0003    10-Jan-2011
6             0006    10-Apr-2018
7             0003    10-Apr-2016
8             0006    10-Apr-2015
9             0001    10-Apr-2017

This is my code below

SELECT userID, COUNT(userID) AS count
FROM BookingTable 
GROUP BY userID
HAVING COUNT(userID) >2

Here is the result from my query above

userID  count
0001      4
0003      3

From the table i would like to add where the timebooked is from past year to current date.

whalesboy
  • 21
  • 8

1 Answers1

2

You may use sysdate - interval '1' year to represent today's date one year ago:

SELECT userID, COUNT(userID) AS count
FROM BookingTable 
WHERE Timebooked BETWEEN SYSDATE - INTERVAL '1' year AND SYSDATE
GROUP BY userID
HAVING COUNT(userID) > 2

As @Wernfried correctly pointed out below, the above would fail for February 29 in a leap year. Instead, use this workaround:

WHERE Timebooked BETWEEN ADD_MONTHS(SYSDATE, -12) AND SYSDATE
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360