Share via

Query Listdates from the last 30 days

JJK 20 Reputation points
2023-11-16T06:40:46.4366667+00:00

Hi.

I have a table. Inside are the Listdates.

  • 2023-08-20
  • 2023-09-12
  • 2023-10-23
  • 2023-10-15
  • 2023-11-23
  • 2023-10-09
  • 2023-11-06

I use this query to get Listdates from the last 30 days.

SELECT * 
FROM test 
WHERE  DATEDIFF(day,ListDate,GETDATE()) <=30;

But I got 2023-11-23, which should not be here.

Help.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
0 comments No comments

Answer accepted by question author
  1. Anonymous
    2023-11-16T06:50:34.8933333+00:00

    Hi @JJK

    You can try this.

    create table test(ListDate datetime);
    insert into test values
    ('2023-08-20'),
    ('2023-09-12'),
    ('2023-10-23'),
    ('2023-10-15'),
    ('2023-11-23'),
    ('2023-10-09'),
    ('2023-11-06');
    
    select * from test 
    where ListDate >= DATEADD(day,-30,GETDATE()) and ListDate <= getdate();
    

    Output:

    User's image

    Best regards,

    Percy Tang

    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Wilko van de Velde 2,241 Reputation points
    2023-11-16T07:20:29.83+00:00

    Hi JJK,

    The function datediff will also return negative values. Look at the result of this query:

    select *, DATEDIFF(day,ListDate,GETDATE()) from test 
    

    Result:

    User's image

    As you can see 2023-11-23, has a datediff less then 30 so it will turn up in your result.

    You can fix it by using between in the where:

    SELECT * 
    FROM test 
    WHERE  DATEDIFF(day,ListDate,GETDATE()) between 0 and 30;
    

    Or use the query of @Anonymous

    Kind regards,

    Wilko


    Please do not forget to "Accept the answer” wherever the information provided helps you, this can be beneficial to other community members. If you have extra questions about this answer, please click "Comment".

    1 person found this answer helpful.
    0 comments No comments

  2. JJK 20 Reputation points
    2023-11-17T06:13:21.4533333+00:00

    Thank you both!

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.