Create Date from two cols in mySql - 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?

Related

MySQL: Get date based on the nth day of the week on a particular month/year

I need to recover/create a date based on the nth day of the week of any given year and month.
Eg. I want to know which day will be the third Monday of December 2020.
Any suggestions?
Test the expression:
SELECT (#year*10000 + #month*100 + 1) + INTERVAL 7 * #weeknumber + #weekday - WEEKDAY(#year*10000 + #month*100 + 1) - 7*(#weekday > WEEKDAY(#year*10000 + #month*100 + 1) - 1) DAY
where
#year - the year (2020 in the question example)
#month - the month (12)
#weekday - needed weekday (0) (0-Monday,1-Tuesday,...6-Sunday)
#weeknumber - the number of needed day in the month (3)
One method is brute force method. Generate all the dates in the month and choose the one you want:
with recursive dates as (
select date('2020-12-01') as dte
union all
select dte + interval 1 day
from dates
where dte < last_day(dte)
)
select *
from (select d.*, dayname(dte) as dname,
row_number() over (partition by dayname(dte) order by dte) as cnt
from dates d
) d
where cnt = 3 and dname = 'Monday';
You could, of course, use a calendar table instead. This approach makes it easy to extend the request -- the first month and the fourth Thursday, if that is what you really want.
Here is a db<>fiddle.

MySQL select records for the past 3 months

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) ;

How to get last year's date range?

I would like to get a date range between LastYear/1/1 until LastYear/12/31
I know I could do this
date_sub(now(), interval 1 year). But this would get me 2013/03/08. Not sure how to change the day and the month.
SELECT *
FROM orders
WHERE dispatch_date between `LastYear/1/1` AND `LastYear/12/31`
You can easy to create the required dates:
SELECT *
FROM orders
WHERE dispatch_date >= MAKEDATE(YEAR(NOW()) - 1, 1) -- first day of previous year
AND dispatch_date < MAKEDATE(YEAR(NOW()), 1) -- first day of current year
I would suggest you to use YEAR().
SET #LastYear = YEAR(DATE_SUB(NOW(),INTERVAL 1 YEAR));
SELECT *
FROM orders
WHERE dispatch_date
BETWEEN CONCAT(#LastYear,'-01-01') AND CONCAT(#LastYear,'-12-31')

Returning records from the last 3 months only in MySQL

I have a table with a timestamp field. How do I get data from the last 3 months?
In particular, March is my current month let say, 03/2012. I need to return records from the months March, February, and January only.
3 months before today:
select * from table where timestamp >= now()-interval 3 month;
Start with first of month:
select * from table where timestamp >= last_day(now()) + interval 1 day - interval 3 month;
To get the first day of the current month, you could use this:
DATE_FORMAT(CURDATE(), '%Y-%m-01')
if current date is 2013-03-13, it will return 2013-03-01, and we can just substract 2 months from this date to obtain 2013-01-01. Your query could be like this:
SELECT *
FROM yourtable
WHERE data >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH
I know this is an old question, but to possibly save others time and to sum the above answers up for the case of needing (1) dates from current month and (2) dates from the prior 2 months (common when displaying data statistics):
WHERE ((timestamp >= NOW() - DATE_FORMAT(CURDATE(), '%Y-%m-01'))
OR (timestamp >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH))
Assuming you're using SQL Server (Oracle, MySQL and others have similar date functions), you can use the dateadd function to add or subtract an interval to the current date.
If you want a full three months, you can subtract 3 months from today : DATEADD(m,-3,getdate())
But, as you state, you only want data from January, February and March. You have to make some calculation based on today's date: dateadd(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate())) + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))
And in the end, get a query like
SELECT fields
FROM table
WHERE timestampfield > DATEADD(m,-2, CONVERT(datetime, CONVERT(VARCHAR(2), MONTH(getdate())) + '/01/' + CONVERT(VARCHAR(4), YEAR(getdate()))))
--- edit ---
erf, I just noticed the "mysql" tag... you can get more information on MySQL date functions here : https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Another possibility would be:
SELECT * WHERE your_date_column > LAST_DAY(CURRENT_DATE - INTERVAL 3 MONTH);
Use this code here to get the previous 3 months from a certain date
SELECT * FROM table WHERE date_column>= DATE_FORMAT(current_date(), '%Y-%m-01') - INTERVAL 3 MONTH and date_column< DATE_FORMAT(current_date(), '%Y-%m-01')
WHERE ((timestamp >= NOW() - DATE_FORMAT(CURDATE(), '%Y-%m-01'))
OR (timestamp >= DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 2 MONTH))

MySQL query that selects record based on todays date between date range set in record

I have a table exhibitions which has 2 columns startDate and endDate. I want to select the records based on today's date. So if today is '2012-05-24', I would want the record that's startDate would be '2012-05-01' and endDate would be '2012-05-31'.
I have used the query in reverse, find records between '2012-05-01' and '2012-05-31', but not based on today's date. Any direction would be helpful.
SELECT *
FROM exhibitions
WHERE startDate > DATE_FORMAT(CONCAT(SUBSTR(NOW(),1,8),'01'),'%a')
AND endDate < DATE_FORMAT(LAST_DAY(NOW()),'%a')
Try this:
Select *
FROM exhibitions
WHERE startDate < CURRENT_DATE() and endDate > CURRENT_DATE()
UPDATE:
You need to find the first day of the month and last day of the month. There is a LAST_DAY() function but no FIRST_DAY() function.
To find the first day of the month based on today's date you can use:
DATE_ADD(LAST_DAY(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)), INTERVAL 1 DAY)
To find the last day of the month based on today's date you can use:
LAST_DAY(CURRENT_DATE())
The end query would be like this:
Select *
FROM exhibitions
WHERE Startdate = LAST_DAY(CURRENT_DATE())
AND
endDate = DATE_ADD(LAST_DAY(DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH)), INTERVAL 1 DAY)