I am struggling with extracting information from my database. Here is an example of the table...
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
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] <= dateadd("d",start_date,(class_days-1))
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] < dateadd("d",start_date,(class_days))
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
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
Dig Deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.