MySQL year interval that Includes the entire month from the previous year - mysql

I have MySQL condition that grabs a time interval from now back x number of months. Typically, this will be set to 13 months so you can compare the current month to that of last year.
'created > DATE_SUB(now(), INTERVAL ' . $timeInterval . ' MONTH)'
So for example last January compared to this January, but I'd like to include all of the previous years month. So instead of January 20, 2015 to January 20, 2016 I would have January 01, 2015 to the current date in January this year until February 1st.

I'd use DATE_FORMAT to make it quick and easy, replace the "day" part of the date with a constant. Then subtract your number of months...
... t.created > DATE_FORMAT(NOW(),'%Y-%m-01') - INTERVAL ? MONTH
As a demonstration of what is returned by that expression, we can test it using a simple SELECT statement:
SELECT NOW(), DATE_FORMAT(NOW(),'%Y-%m-01') - INTERVAL 12 MONTH
NOW() DATE_FORMAT(NOW(),'%Y-%m-01') - INTERVAL 12 MONTH
------------------- -------------------------------------------------
2016-01-27 21:01:02 2015-01-01
FOLLOWUP
Are you sure you want a "greater than" comparison, rather than a "greater than or equal to" comparison >= ?
There are other approaches to generating that date value to compare to. You could use DATE(NOW()) or CURDATE() to return the current date with no time component.
And use the DAY() function to get the numeric value of the current day, and then subtract that (minus 1) as a number of days. For example, something like this:
>= DATE(NOW()) - INTERVAL DAY(NOW())-1 DAY - INTERVAL 12 MONTH
That seems messier and more complicated. I think it's easier to understand stuffing in the '-01' as the day part.

created > str_to_date(concat(year(now())-1, '-01-01'), '%Y-%m-%d')
Or if you need not all previous year:
select str_to_date(concat(year(now())-1, '-', month(now()),'-01'), '%Y-%m-%d')

Related

Query of current date in time mysql

I have a column of time with type datetime in mysql called createdAt, so I want find out the data with time range like this
createdAt >= SUBDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), WEEKDAY(curdate()))
and createdAt <= ADDDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), 6-WEEKDAY(curdate()))
assume createdAt curdate() based on this question made are october 8th 2020, so that time range will be 28th september 2020 until 04th october 2020
But when I check manually, if I add some time range in another media, why the counting is little bit more different? For example: using this query, count of transaction is 87 transaction, but then I used another media to count the transaction between 28th september 2020 00:00:00 until 04th october 23:59:59 its 90 transaction, is that any I can add in query for time range in my query date range?
Your expression ADDDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), 6-WEEKDAY(curdate())) returns only date part of last week day, so all data after start this day is not included.
You have couple of options to solve this:
Round createdAt to date withot time part:
SELECT *
FROM your_table
WHERE DATE(createdAt) BETWEEN
SUBDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), WEEKDAY(curdate())) AND
ADDDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), 6-WEEKDAY(curdate()));
Use strong less condition with next day:
SELECT *
FROM your_table
WHERE
createdAt >= SUBDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), WEEKDAY(curdate())) AND
createdAt < ADDDATE(DATE_SUB(curdate(), INTERVAL 1 WEEK), 7-WEEKDAY(curdate()));

How to find next date from time in mysql

I want to know is it possible in mysql query.. when I say give me date when it is 9am.. the return answer is depends upon current time when it is 8am it give me today's date. when it is 10pm it gives me tomorrow date. how it is possible in mysql query.
You can use SUBSTRING_INDEX(CURTIME(), ':', 1) to get the hours of current time.
As I understood you want to get tomorrow date, if it is 10pm or later
Example given:
SELECT
CASE
WHEN SUBSTRING_INDEX(CURTIME(), ':', 1) >= 22
THEN DATE_ADD(CURDATE(), INTERVAL 1 DAY)
ELSE CURDATE()
END
Source: http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/sql_dates.asp.html
You can get the hour value from a given datetime expression, using HOUR function. CURDATE() function is used to return the current date. You can add/subtract 'integers' to it get the date corresponding to current date +/- 'integer days' . Assuming that the time >= 10 pm returns next day:
SELECT IF(HOUR(`datetime_field`) > 22, CURDATE(), CURDATE() + 1);
You could just add 2 hours
SELECT DATE(DATE_ADD(NOW(), INTERVAL 2 HOUR));
This will then return tomorrow’s date for anytime after 10pm.

How to find the first Sunday of the month in MySQL?

I did not find any of examples for MySQL - all of them were quite complicated.
How can I SELECT the first Sunday of the month?
So choose the first day of the month: 2012-01-01 (or whatever month and year you want).
Get the weekday index of the date. Indexes here are from 0 to 6.
Subtract that index from 6 and you will get how many days you need to add until the date is Sunday.
Add that amount of days to the chosen day.
SELECT DATE_ADD("2012-01-01 10:00:00", INTERVAL (6 - WEEKDAY("2012-01-01 10:00:00")) DAY);
Or:
SELECT DATE_ADD("2012-01-01", INTERVAL (6 - WEEKDAY("2012-01-01")) DAY);
So choose the first day of the month: 2021-08-01 (or whatever month and year you want).
SELECT ADDDATE( '2021-08-01' , MOD((8-DAYOFWEEK('2021-08-01')),7))

MySQL round date to the start of the week and month

For "2012-07-12", how can I get the start of the week, i.e., "2012-07-08", and start of the month, i.e., "2012-07-01"?
First day of the month:
SELECT DATE_FORMAT('2007-07-12', '%Y-%m-01');
output: 2007-07-01
First day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFWEEK('2007-07-12')-1 DAY);
output: 2007-07-08
MySQL reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
Same answer as Borophyll's, but I have changed the behavior of the first day of the month to return a date, not just a string which avoids date formatting/parsing mentioned in user151220's answer.
First day of the month:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFMONTH('2007-07-12') - 1 DAY);
output: 2007-07-01
First day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFWEEK('2007-07-12') - 1 DAY);
output: 2007-07-08
MySQL reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
For those who need Monday as the first day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL WEEKDAY('2007-07-12') DAY);
output: 2007-07-09
This relies on the WEEKDAY function, which starts with Monday instead of DAYOFWEEK, which starts with Sunday.
The DATE_FORMAT reply from Borophyll is very good, but gives a string rather than a date. So can't be compared easily.
If you need to use this as a comparison to a date field, use str_to_date to reverse it back to date rather than string.
select x from y where date >= str_to_date( DATE_FORMAT(now()-interval 12 month,'Y-%m-01'), '%Y-%m-%d')
If you are (say) looking at 12 months sales figures, but you want to always start off from the 1st of a month.
This will work if you want to just code it and forget about it, it will use datetime now and always return MTD results-
where date_completed between date_sub(date(now()), INTERVAL dayofmonth(now()) -1 day) and now()

Get ToDate , FromDate from Week Number in MySQL

I easily get Week Number using MySql Week function like this WEEK(SYSDATE())
I just wanted to know how to get from and to date using week number in MySQL.
Result required:
Week No From date To date
Week 25 June 18, 2012 June 24, 2012
This works great for this kind of job:
SELECT
ADDDATE(CURDATE(), INTERVAL 1-DAYOFWEEK(CURDATE()) DAY) _From,
ADDDATE(CURDATE(), INTERVAL 7-DAYOFWEEK(CURDATE()) DAY) _To;
Beware that first day of week here is Sunday. It may depends on your country convention ;)