Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 30 day records from today date in SQL Server

I have small question about SQL Server: how to get last 30 days 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 this table data i want output like below

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

I tried this query

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

but it now give exactly result. Please tell me how to solve this issue in SQL Server

like image 431
user3224208 Avatar asked Dec 15 '14 08:12

user3224208


People also ask

How can I get last 30 days from today's date in SQL?

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

How do I get 30 days in SQL?

Just realised, this is written in T-Sql (Sql Server), if the answer is needed for MySql then something like: SELECT DATE_ADD(NOW(), INTERVAL -30 DAY) is the equivalent.

How do I get previous days data in SQL Server?

To get yesterday's date, you need to subtract one day from today's date. Use GETDATE() to get today's date (the type is datetime ) and cast it to date . In SQL Server, you can subtract or add any number of days using the DATEADD() function. The DATEADD() function takes three arguments: datepart , number , and date .

How can I get last 7 days data in SQL?

Here's the SQL query to get records from last 7 days in MySQL. In the above query we select those records where order_date falls after a past interval of 7 days. We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.


2 Answers

Add one more condition in 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  
like image 54
Pரதீப் Avatar answered Sep 29 '22 04:09

Pரதீப்


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

where DATEDIFF(day,pdate,GETDATE()) < 31 
like image 37
danish Avatar answered Sep 29 '22 04:09

danish