I have function get day of week and week from current day in mysql
It look like.
select
DATE_FORMAT(now(), '%U') as w,
DATE_FORMAT(now(), '%w') as day_of_w;
It return w is 37 and day_of_week is 1. How to get correct value w is 37 and day_of_week is 1 of previous year.
I using
select
DATE_FORMAT(now() interval 1 year, '%U') as w,
DATE_FORMAT(now() interval 1 year, '%w') as day_of_w;
But SQL cannot execute.
The function to turn a string into a date is STR_TO_DATE. If you want to get the date for week 37, day 1 in 2019, you could use
select str_to_date('37 1 2019', '%U %w %Y')
If you want the date for today's week and day number in last year:
select str_to_date(concat_ws(' ', date_format(current_date, '%U'),
date_format(current_date, '%w'),
year(current_date) - 1),
'%U %w %Y')
Be aware though, that some years have a week 53 while others don't. If you run this query in a year's 53rd week, you don't get a valid result.
select DAYOFWEEK(now()) day_of_week, week(now()) week from dual
your query has syntactical problem. you forgot +/- symbol
select DATE_FORMAT(now() + interval 1 year, '%U') as w
,DATE_FORMAT(now() + interval 1 year, '%w') as day_of_w;
You just need to use DATE_ADD function in MYSQL to change the date to last year.
select DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%U') as w
,DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%w') as day_of_w;
Result:
36 6
Current and last year date:
select now() as curr_yr_date, DATE_ADD(now(), INTERVAL -1 YEAR) as last_yr_date;
Result:
2020-09-14 07:13:24 2019-09-14 07:13:24
Related
I'm building a weekly report using MySQL queries. First I get week number by
SELECT WEEK(CURDATE());
Then I need to display the starting date of the week (Monday for my region). How to do it with MySQL only?
Thanks!
If you need date of monday in current week
try this:
SELECT DATE_ADD(CURDATE(), INTERVAL - WEEKDAY(CURDATE()) DAY)
It return you monday date of current week.
In fact, DATE_ADD is not necessary and complicates the logic. Here is the simplest version for "Date of the first day of the current week":
select date(curdate() - interval weekday(curdate()) day)
which would translate to:
get the date() part of the (current date - an interval of N days)
where N = today's number in the week, i.e. Thu is number 3 (for a week starting on Monday)
Then, getting the Monday of previous week, is:
select date(curdate() - interval weekday(curdate()) day - interval 1 week)
which is more readable IMHO.
For thhose who need the Monday date of the current week.
If you count Monday as the first day of the week:
SELECT STR_TO_DATE(CONCAT(YEARWEEK(NOW(), 1),'Monday'), '%x%v %W');
If you count Sunday as the first day of the week:
SELECT STR_TO_DATE(CONCAT(YEARWEEK(NOW()),'Monday'), '%X%V %W');
SELECT DATE_ADD((SELECT curdate() - INTERVAL (WEEKDAY(curdate())+1)DAY),INTERVAL 1 DAY) as current_monday
-- current week monday
(SELECT DATE_ADD(CURDATE(), INTERVAL - WEEKDAY(CURDATE()) DAY))
-- current week friday
SELECT DATE_ADD((SELECT DATE_ADD(CURDATE(), INTERVAL - WEEKDAY(CURDATE()) DAY)),INTERVAL 4 DAY);
-- next week monday
SELECT date(curdate() - interval weekday(curdate()) day + interval 1 week);
-- next week friday
SELECT DATE_ADD((SELECT date(curdate() - interval weekday(curdate()) day + interval 1 week)),INTERVAL 4 DAY);
In fact, we substruct days, not add them. Just more simple expression:
DATE_SUB( CURDATE(), INTERVAL WEEKDAY( CURDATE() )
You can use this:
<?php
$week = date('W');
$year = date('Y');
echo $date1 = date(
'Y-m-d',
strtotime($year . 'W' . str_pad($week, 2, '0', STR_PAD_LEFT))
);
?>
I want to get no of downloads per month from current date since last 1 year
This is my query
SELECT a.imei,
a.numberofdownloads,
a.numberofdownloads AS aug,
a.numberofstreams AS jul,
a.numberofdownloads AS jun,
a.numberofstreams,
b.datetime
FROM activeusers a,
imei_downloadstream b
WHERE a.imei = b.imei
AND b.datetime BETWEEN Date_format(Curdate() - INTERVAL 1 month,
'%Y-%m-01 00:00:00'
) AND
Date_format(Last_day(Curdate() -
INTERVAL 1 month),
'%Y-%m-%d 23:59:59')
AND Date_format(Last_day(Curdate() - INTERVAL 2 month),
'%Y-%m-%d 23:59:59')
AND Date_format(Last_day(Curdate() - INTERVAL 3 month),
'%Y-%m-%d 23:59:59')
LIMIT 10;
You are very close. You need a way to determine the first day of the month from the current date.
You have almost figured that out. It is this:
DATE(DATE_FORMAT(CURDATE(), '%Y-%m-01'))
Then you need to use a GROUP BY clause featuring that expression. Something like this will do it.
SELECT a.imei,
SUM(a.numberofdownloads) AS numberofdownloads,
DATE(DATE_FORMAT(b.datetime, '%Y-%m-01')) AS month_beginning
FROM activeusers a,
JOIN imei_downloadstream b ON a.imei = b.imei
WHERE b.datetime >= DATE(DATE_FORMAT(CURDATE(), '%Y-%m-01')) - INTERVAL 12 MONTH
AND b.datetime < DATE(DATE_FORMAT(CURDATE(), '%Y-%m-01'))
GROUP BY DATE(DATE_FORMAT(b.datetime, '%Y-%m-01')), a.imei
See what's going on here? You're choosing all the records having dates between the first of the month twelve months ago and the first of the present month. Then you're computing the beginning date of the month for each record, then you're grouping by that value.
This works flawlessly if you get your JOIN right. Here is a more detailed writelup.
http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
How would I go about retrieving records from the last three months of the previous year? I was thinking it would be:
Date_add(curdate() , interval '-1 2' year_month)
Try this:
WHERE my_date_column BETWEEN
SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) + 91 DAY) AND
SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) DAY)
91 is one less than 31 + 30 + 31, because BETWEEN is inclusive.
Note that if your column is a datetime type, you'll need the end value to be the last second of the day:
SUBDATE(SUBDATE(CURDATE(), INTERVAL DAYOFYEAR(CURDATE()) - 1 DAY), INTERVAL 1 SECOND)
See SQLFiddle of these expressions generating correct values.
Assuming you date column is named "date", something like:
SELECT
*
FROM
table
WHERE
YEAR(date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
AND
MONTH(date) BETWEEN 10 AND 12
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))
I need to select data from MySQL database between the 1st day of the current month and current day.
select*from table_name
where date between "1st day of current month" and "current day"
Can someone provide working example of this query?
select * from table_name
where (date between DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), interval 30 day), interval 1 day) AND CURDATE() )
Or better :
select * from table_name
where (date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )
I was looking for a similar query where I needed to use the first day of a month in my query.
The last_day function didn't work for me but DAYOFMONTH came in handy.
So if anyone is looking for the same issue, the following code returns the date for first day of the current month.
SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);
Comparing a date column with the first day of the month :
select * from table_name where date between
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE
select * from table_name
where `date` between curdate() - dayofmonth(curdate()) + 1
and curdate()
SQLFiddle example
I have used the following query. It has worked great for me in the past.
select date(now()) - interval day(now()) day + interval 1 day
try this :
SET #StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET #EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= #StartDate and date < #EndDate);
Complete solution for mysql current month and current year, which makes use of indexing properly as well :)
-- Current month
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
-- Current year
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFYEAR(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
select * from table
where date between
(date_add (CURRENT_DATE, INTERVAL(1 - DAYOFMonth(CURRENT_DATE)) day)) and current_date;
select * from <table>
where <dateValue> between last_day(curdate() - interval 1 month + interval 1 day)
and curdate();
I found myself here after needing this same query for some Business Intelligence Queries I'm running on an e-commerce store. I wanted to add my solution as it may be helpful to others.
set #firstOfLastLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)))-1 DAY);
set #lastOfLastLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH));
set #firstOfLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)))-1 DAY);
set #lastOfLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH));
set #firstOfMonth = DATE_ADD(#lastOfLastMonth, INTERVAL 1 DAY);
set #today = CURRENT_DATE;
Today is 2019-10-08 so the output looks like
#firstOfLastLastMonth = '2019-08-01'
#lastOfLastLastMonth = '2019-08-31'
#firstOfLastMonth = '2019-09-01'
#lastOfLastMonth = '2019-09-30'
#firstOfMonth = '2019-10-01'
#today = '2019-10-08'
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
SELECT date_sub(current_date(),interval dayofmonth(current_date())-1 day) as first_day_of_month;
I had some what similar requirement - to find first day of the month but based on year end month selected by user in their profile page.
Problem statement - find all the txns done by the user in his/her financial year. Financial year is determined using year end month value where month can be any valid month - 1 for Jan, 2 for Feb, 3 for Mar,....12 for Dec.
For some clients financial year ends on March and some observe it on December.
Scenarios - (Today is `08 Aug, 2018`)
1. If `financial year` ends on `July` then query should return `01 Aug 2018`.
2. If `financial year` ends on `December` then query should return `01 January 2018`.
3. If `financial year` ends on `March` then query should return `01 April 2018`.
4. If `financial year` ends on `September` then query should return `01 October 2017`.
And, finally below is the query. -
select #date := (case when ? >= month(now())
then date_format((subdate(subdate(now(), interval (12 - ? + month(now()) - 1) month), interval day(now()) - 2 day)) ,'%Y-%m-01')
else date_format((subdate(now(), interval month(now()) - ? - 1 month)), '%Y-%m-01') end)
where ? is year end month (values from 1 to 12).
The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.
The fastest solution to the real problem of getting the first day of the month returns VARCHAR:
SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;
The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:
SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;
The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself 😊
In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.
So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:
SELECT * FROM table_name
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;
I used this one
select DATE_ADD(DATE_SUB(LAST_DAY(now()), INTERVAL 1 MONTH),INTERVAL 1 day) first_day
,LAST_DAY(now()) last_day, date(now()) today_day
All the responses here have been way too complex. You know that the first of the current month is the current date but with 01 as the date. You can just use YEAR() and MONTH() to build the month date by inputting the NOW() method.
Here's the solution:
select * from table_name
where date between CONCAT_WS('-', YEAR( NOW() ), MONTH( NOW() ), '01') and DATE( NOW() )
CONCAT_WS() joins a series of strings with a separator (a dash in this case).
So if today is 2020-08-28, YEAR( NOW() ) = '2020' and MONTH( NOW() ) = '08' and then you just need to append '01' at the end.
Voila!
Get first date and last date from month and year.
select LAST_DAY(CONCAT(year,'.',month,'.','01')) as registerDate from user;
select date_add(date_add(LAST_DAY(end_date),interval 1 DAY),interval -1 MONTH) AS closingDate from user;
SET #date:='2012-07-11';
SELECT date_add(date_add(LAST_DAY(#date),interval 1 DAY),
interval -1 MONTH) AS first_day