Home > database >  Get data from certain date to last 10 days in SQL
Get data from certain date to last 10 days in SQL

Time:09-07

I want to get data from certain date to last 10 days. I have tried the following code but it is not working.

DECLARE @wrking_date DATE = '2022-02-08'
SELECT 
    a,
    CAST(LogDate as date) as theDate,
    b,c
FROM magic_table
Where b = '123'
AND @wrking_date >= DATEADD(DAY,10, GETDATE())

What I am doing wrong ?

EDIT

I have also tried adding AND LogDate between '2022-02-08' and DATEADD(DAY, -10, '2022-02-08') this does not work

CodePudding user response:

As it's currently written, your query doesn't get filtered with your AND condition because neither GETDATE() not @wrking_date are part of the queried table. I'm assuming you want to filter based on the column LogDate. To get the values between @wrking_date and 10 days ago, you can use BETWEEN:

AND LogDate BETWEEN @wrking_date AND DATEADD(DAY, -10, GETDATE())

Notice this: To get the date from 10 days ago, you need to use -10 in the DATEADD function.

Edit

As I got from your comments, you're trying to get the data between the defined @working_date and 10 days back from there. You could achieve that by using this:

AND LogDate BETWEEN DATEADD(DAY, -10, @wrking_date) AND @wrking_date
  • Related