Search code examples
sql-serverdate-range

How to calculate in SQL Server range of dates without using specific dates?


I have this question on an assignment:

Write a SQL query to display all details of transactions that were made at least one week before the pickup date.

We've been instructed not to hard code for this assignment (e.g. don't look up the values in the table to determine how to calculate). We are to make the code calculate the solution regardless of the input values.

I have a Transaction table with a TransactionDate and a PickupDate column, both defined as date datatypes in YYYY-MM-DD format.

I'm new to SQL Server and have been racking my brain as to how to do this. Any guidance in the right direction would be appreciated!


Solution

  • You can simply use where clause:

    SELECT * 
    FROM TRANSACTION
    WHERE TRANSACTION_DATE < DATEADD(DAY, -7,  PICKUP_DATE);
    

    Here, we compared TRANSACTION_DATE with PICKUP_DATE minus one week and it will include all the records where transaction is made one week before pickup.