Search code examples
sqlsql-serverdatetimetimestampsql-timestamp

How to select the SQL data from just 20 days using the TimeStamp


How can i just use the data of the previous 20 days using the TimeStamp. In the below code i am selecting the Timestamp anything above this timstamp i wanted to select and later insert it. But i not interested in all the data which is in database but i need the data of 20 days from that particular timestamp date. How can i achieve it. What i tried is in below.

My SQL server query is as follows:

SELECT [LogID]
      ,[TimeStamp]
      ,[Artikel_Nr]
      ,[Percentage_Nr]
from [Database1].[dbo].[Tabel1]
  where [TimeStamp] > 2018-02-12 06:02:18.77 AND SELECT DATEADD(DAY,-20,GETDATE())

I am not sure the above line for selecting last 20 days i right. If not please correct me.


Solution

  • The will be an error on SELECT DATEADD(DAY,-20,GETDATE()) you can use DATEADD(DAY,-20,GETDATE()) directly.

    If you want to previous 20 days you can try between the start day and end date.

    1. start day previous 20 days DATEADD(DAY,-20,GETDATE())
    2. end date only use GETDATE() to get current datetime.

    then use Between

    SELECT [LogID]
          ,[TimeStamp]
          ,[Artikel_Nr]
          ,[Percentage_Nr]
    from [server1].[dbo].[Database1]
    where [TimeStamp]  between DATEADD(DAY,-20,GETDATE()) and GETDATE()