MySQL select records for the past 3 months - mysql

what will be the smartest way to select all rows from MySQL table for the past 3 months if the table has the following columns:
| id (int) | year (int)| month (int) |
Considering that if the current month & year are for example 2.2016 I need to select all records for 11.2015 & 12.2015 & 1.2016
It is easy if the current month is greater than 3 because all months that I need to select are in the same year so I can subtract 3 from the current month and run simple query
SELECT * FROM mytabe where year=2016 and month >= xx

Select * from mytable where STR_TO_DATE(concat(year,"-",month,"-01"),'%Y-%m-%d')>date_sub(curdate(),Interval 3 month) ;
The above query will get fetch year and month from date 3 months before today

You can select three Months records by these queries follow this.
The columnName means which column data want you select.
The tableName means which table data want you select.
The dateColumnName means which column date base you want to select data.
It would return Last Month data from today.
SELECT columName FROM tableName WHERE dateColumName BETWEEN ( DATE(NOW()) - INTERVAL 1 MONTH) AND Date(Now())
It would return Second Last Month data from today.
SELECT columName FROM tableName WHERE dateColumName BETWEEN ( DATE(NOW()) - INTERVAL 2 MONTH) AND ( DATE(NOW()) - INTERVAL 1 MONTH)
It would return Third Last Month data from today.
SELECT columName FROM tableName WHERE dateColumName BETWEEN ( DATE(NOW()) - INTERVAL 3 MONTH) AND ( DATE(NOW()) - INTERVAL 2 MONTH)
May It help to others.

Please try this
Select * from mytable where STR_TO_DATE(concat(year,"-",month,"-01"),'%Y-%m-%d')>date_sub(curdate(),Interval 3 month) ;

Related

How to get rows from MySQL table with two field to order by?

I have a table in MySQL with fields:
id - int;
date - datetime;
rating - decimal(3,2);
and so on, other fields are not necessary in this selection.
There are about 6000 rows in the table.
I have to get rows from the table that is ordered by rating ASC for the last 6 months and then other rows ordered by id ASC.
How can I do it?Will it work fast?
I would do something like this to achieve that:
select *
from tbl
order by case
when date >= DATE_ADD(curdate(), INTERVAL -6 MONTH) then
rating
else id
end ASC;
You need to make sure that all the records from the last 6 months come first in the result, and then worry about ordering by rating or id. You can do that by ordering on the boolean
date >= CURDATE() - INTERVAL 6 MONTH
first, and then on either rating or id as appropriate. For example:
SELECT *
FROM data
ORDER BY date >= CURDATE() - INTERVAL 6 MONTH DESC,
CASE WHEN date >= CURDATE() - INTERVAL 6 MONTH THEN rating
ELSE id
END

SELECT from database date where date is today and multiple

There are a method with SQL to SELECT from one database the date records where the date is today and the date is multiple of two years.
For example, i have a table call "list". That table have two column, 'ID' and 'last_date'. One of this record is: ID = '1' and date = '17-03-2015'
I need to select all record where the date is the date on the table + 2 year. For example today the query will return the ID 1.
Thanks to all.
Use DATE_SUB() to subtract 2 years from today's date, and compare that to the column.
SELECT id
FROM list
WHERE last_date = DATE_SUB(CURDATE(), INTERVAL 2 YEAR);
This is a little better than #Teja's solution because it only has to do the date arithmetic once, rather than for every row in the table. And if there's an index on the last_date column, it will be able to use it to find the rows quickly.
We can write an expression that returns a date value that is exactly two days before today's date:
SELECT DATE(NOW()) + INTERVAL -2 YEAR
We can use an expression in the WHERE clause of a query. If the column in the table we want to check is defined as DATE datatype:
SELECT t.id
FROM mytable t
WHERE t.mydatecol = DATE(NOW()) + INTERVAL -2 YEAR
If it's defined as a DATETIME, the normal pattern would be range check
SELECT t.id
FROM mytable t
WHERE t.mydatecol >= DATE(NOW()) + INTERVAL -2 YEAR
AND t.mydatecol < DATE(NOW()) + INTERVAL -2 YEAR + INTERVAL 1 DAY
If the column is stored as a VARCHAR in a non-canonical format e.g. DD-MM-YYYY then we could either attempt to convert that to a DATE using STR_TO_DATE (which we don't like to do because the query can't make effective use of a index), or we could convert our generated date value into the required string format for an equality comparison:
SELECT t.id
FROM mytable t
WHERE t.ddmmyyyy = DATE_FORMAT(DATE(NOW()) + INTERVAL -2 YEAR,'%d-%m-%Y')
That would get us exact match to '17-03-2015', but not to '17-3-2015'. And we have to do equality test or IN list, we can't do range check, because the value stored in the column isn't canonical.
If we need to look for multiple dates... today, two years ago, four years ago, six years ago, ... we can generate a list of dates and perform a join operation. (Assuming that mydatecol is defined as DATETIME...)
SELECT t.id
FROM ( SELECT DATE(NOW()) + INTERVAL 0 YEAR AS dt
UNION ALL SELECT DATE(NOW()) + INTERVAL -2 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -4 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -6 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -8 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -10 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -12 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -14 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -16 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -18 YEAR
UNION ALL SELECT DATE(NOW()) + INTERVAL -20 YEAR
) l
JOIN mytable t
WHERE t.mydatecol >= l.dt + INTERVAL 0 DAY
AND t.mydatecol < l.dt + INTERVAL 1 DAY

MySQL Query to get all rows for 2 months ago

I need to do a select where I can chose to see results for current month, previous month, 1 month ago, 2 months ago, 3 months ago.
I found this question: MySQL: Query to get all rows from previous month, but I'm stuck with a filter that will get me all the results for 2 months ago from first to last day of the month.
I tried with this but it doesn't work:
SELECT * FROM table
AND MONTH(date_created) = MONTH(1 MONTH - INTERVAL 2 MONTH);
Try this:
SELECT * FROM table
WHERE MONTH(date_created) = MONTH(NOW() - INTERVAL 2 MONTH)
AND (
YEAR(date_created) = YEAR(NOW())
OR
YEAR(date_created) = YEAR(NOW() - INTERVAL 2 MONTH)
);
Returning records CREATED PRIOR the last 2 months only in MySQL.
If you want all rows from 2 months ago, then use logic like this:
WHERE date_created >= DATE_SUB(DATE_SUB(CURDATE(), 1 - DAY(CURDATE())), INTERVAL 2 MONTH) AND
date_created < DATE_SUB(DATE_SUB(CURDATE(), 1 - DAY(CURDATE())), INTERVAL 1 MONTH)
What is this doing? First, it is only applying functions to the current date part of the expression. This allows MySQL to use an index on date_created, if available and appropriate.
The expression DATE_SUB(CURDATE(), 1 - DAY(CURDATE()) is simply a way to get the first day of the month.
You query have an error, correct one would be:
SELECT * FROM table
WHERE MONTH(date_created) = MONTH(DATE_SUB(NOW(),INTERVAL 2 MONTH))
For current month just MONTH(NOW()), replace "2" with any number of months you need (1,3,.. 23)
as mentioned in comments this solution ignores YEAR differences, it just selects all records with the same month, no matter the year
you can filter wrong year results with additional clause:
AND YEAR(date_created) = '2019' # or year you need
Or use more complex query:
SELECT * FROM table
where
date_created between
/* first day of -2 month*/
date_sub(date_sub(now(),interval 2 month), interval (day(now())-1) day)
and
/* last day of -2 month*/
last_day(date_sub(now(),interval 2 month))

Create Date from two cols in mySql

I have a table in my database with two columns: month (1-12) and year (yyyy).
I need to select records between two dates, for exemple
select * from Calendar a where SOMEDATE between STARTDATE and ENDDATE.
So the question is: how can I create the STARTDATE and the ENDDATE from this two columns I have?
...where SOMEDATE between
STR_TO_DATE(CONCAT_WS('-',STARTYEAR,STARTMONTH,1),'%Y-%m-%d')
and
DATE_SUB(
STR_TO_DATE(CONCAT_WS('-',ENDYEAR,ENDMONTH + 1,1),'%Y-%m-%d')
, INTERVAL DAY 1
)
Note that we convert both parts to type date, and use date_sub to subtract a single day from ENDMONTH + 1, since we don't know how many days there are in the relevant month.
You can use this solution to make date from the year and month fields-
SELECT MAKEDATE(year, 1) + INTERVAL month - 1 MONTH FROM calendar;
The apply this one to WHERE condition, e.g. -
SELECT * FROM Calendar a
WHERE
MAKEDATE(year, 1) + INTERVAL month - 1 MONTH BETWEEN
#STARDATE - INTERVAL EXTRACT(DAY FROM #STARDATE) - 1 DAY
AND
#ENDDATE
But I have to ask you about the STARTDATE and ENDDATE criterias. What to do if STARTDATE is '2012-09-20'? Should the query return records with month = 9?

Selecting all records from one year ago till now

I have a table filled with a lot of rows and I need to select all the rows that are less than a year old till now.
The table (called orders) has a DateTime column named order_date, that's the field that determines when the order was placed.
How can I select all the records that have an order_date between now and a full year ago?
select *
from orders
where order_date >= DATE_SUB(NOW(),INTERVAL 1 YEAR);
SELECT * FROM order WHERE order_date >= curdate() - interval 1 year;
To first of month a year ago
SELECT DATE_SUB(DATE_FORMAT(CURRENT_DATE,'%Y-%m-01'),INTERVAL 1 YEAR);
I hope it helps you:
select *
from table
where (order_date BETWEEN '2/15/2011 3:36:18 PM' AND '2/17/2011 9:00:00 PM')