user88866050
user88866050

Reputation: 501

SQL query for getting data for last 3 months

How can you get today's date and convert it to 01/mm /yyyy format and get data from the table with delivery month 3 months ago? Table already contains delivery month as 01/mm/yyyy.

Upvotes: 46

Views: 340573

Answers (6)

Muhammad Zohaib Yunis
Muhammad Zohaib Yunis

Reputation: 536

SELECT * FROM tasks WHERE task_date_creation > date_sub(now(),Interval 3 month)

Upvotes: 0

Bharvi Manvar
Bharvi Manvar

Reputation: 49

Last 3 months record

SELECT *, DATEDIFF(NOW(),`created_at`)as Datediff from `transactions` as t having Datediff <= 90

Upvotes: 0

M.Ali
M.Ali

Reputation: 69574

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(MONTH, -3, GETDATE()) 

Mureinik's suggested method will return the same results, but doing it this way your query can benefit from any indexes on Date_Column.

or you can check against last 90 days.

SELECT * 
FROM TABLE_NAME
WHERE Date_Column >= DATEADD(DAY, -90, GETDATE()) 

Upvotes: 114

Tom McDonough
Tom McDonough

Reputation: 1262

Last 3 months

SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(mm,-3,GETDATE())),0)

Today

SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)

Upvotes: 1

Mithun Arunan
Mithun Arunan

Reputation: 932

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

Upvotes: 20

Mureinik
Mureinik

Reputation: 312136

I'd use datediff, and not care about format conversions:

SELECT *
FROM   mytable
WHERE  DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

Upvotes: 10

Related Questions