Get the latest 30-day records from today in SQL Server

I have a small question about SQL Server: how to get the last 30 days of information from this table

Sample data:

Product :

 Pdate ---------- 2014-11-20 2014-12-12 2014-11-10 2014-12-13 2014-10-12 2014-11-15 2014-11-14 2014-11-16 2015-01-18 

Based on the data in this table, I want the output as shown below

 pdate ------- 2014-11-20 2014-12-12 2014-12-13 2014-11-16 

I tried this request

 SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()). 

but now he gives exactly the result. Please tell me how to solve this problem in SQL Server.

+20
sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2
source share
6 answers

Add another condition to where clause

 SELECT * FROM product WHERE pdate >= DATEADD(day,-30,GETDATE()) and pdate <= getdate() 

Or use DateDiff

 SELECT * FROM product WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30 
+32
source share

You can use DateDiff for this. The where clause in your query will look like this:

 where DATEDIFF(day,pdate,GETDATE()) < 31 
+7
source share

I donโ€™t know why all these complex answers are here, but this is what I would do

 where pdate >= CURRENT_TIMESTAMP -30 

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

+4
source share

This should work fine.

 SELECT * FROM product WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime') 
0
source share

The below request is suitable for the last 30 days of recording

Here I used the overview table, and review_date is the column from the overview table.

 SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY 
0
source share

You can use this to retrieve data for the last 30 days based on a column.

WHERE DATEDIFF (dateColumn, CURRENT_TIMESTAMP) BETWEEN 0 AND 30

0
source share

All Articles