user9630935
user9630935

Reputation: 369

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.

Upvotes: 2

Views: 2637

Answers (3)

Kami
Kami

Reputation: 19427

Try

DECLARE @EndDate DateTime = GETDATE(); -- Specify the date you want to end at
DECLARE @StartDate DateTime = DATEADD(DAY, -20, @EndDate);

SELECT [LogID]
  ,[TimeStamp]
  ,[Artikel_Nr]
  ,[Percentage_Nr]
FROM [Table]
WHERE [TimeStamp] > @StartDate AND [TimeStamp] <= @EndDate 

Upvotes: 2

D-Shih
D-Shih

Reputation: 46239

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()

Upvotes: 1

Fahmi
Fahmi

Reputation: 37473

Try below query: You don't need to select

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

Upvotes: 0

Related Questions