Problem solve Get help with specific problems with your technologies, process and projects.

Calculate an end date from a start date

I am struggling with extracting information from my database. Here is an example of the table...

start_date  class_days  class_name
01/14/2003      6       Test Class 1
01/15/2003      2       Test Class 2
01/15/2003      1       Test Class 3
01/16/2003      5       Test Class 4

I have created an SQL statement that uses the start_date and class_days and calculates a field called end_date. Now I want write an SQL statement that pulls all the classes on a particular day. For example: List all classes for 1/16/2003. I should get three records. I've tried many different statements, but none seem to be working. This is an Access database.

The "gotcha" in this problem is recognizing that you have to subtract 1 from the class_days in the date calculation to come up with the end date.

For example, consider the two classes which start on January 15. One of them lasts two days, the other lasts one day. On which day do they end? The one which lasts two days ends on January 16, and the one which lasts one day ends on January 15, the same day it started!

As to your question, selecting all the classes for a particular day, there are two ways to do it. The first method is to subtract 1 from class_days when calculating the end date for a BETWEEN condition:

select class_name, start_date
  from classes
 where [enter date] 
       between start_date
           and dateadd("d",start_date,(class_days-1))

Note that the BETWEEN syntax is equivalent to:

select class_name, start_date
  from classes
 where start_date <= [enter date] 
   and [enter date] <=

The second way is not to subtract 1, but adjust the condition on the endpoint of the range, from "less than or equal" to simply "less than" --

select class_name, start_date
  from classes
 where start_date <= [enter date] 
   and [enter date] <


Personally, I prefer the "subtract 1" solution, because it generates the correct end date, which you can also use in the SELECT list, and because the SQL is simpler and easier to understand.

For More Information

Dig Deeper on Oracle and SQL