2

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.

user9630935
  • 349
  • 1
  • 4
  • 18
  • 1
    `[server1].[dbo].[Database1]` makes no sense. The first object is the database, second the Schema, and 3rd the object in the database and Schema (I.e. a Table, View). If you were using 4 part naming, then the first part would be the server name. – Thom A Aug 20 '18 at 08:51
  • @Larnu: Sorry my bad, it is [Database1].[dbo].[Tabel1]. I will edit my content. Thanks for noticing. – user9630935 Aug 20 '18 at 09:02

3 Answers3

2

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 
Kami
  • 19,134
  • 4
  • 51
  • 63
1

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()
D-Shih
  • 44,943
  • 6
  • 31
  • 51
0

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())
Fahmi
  • 37,315
  • 5
  • 22
  • 31