I have a table orders and I would like to make a request to retrieve all orders from the month of last year to the same month as now. Example: we are in November, I would like to recover all the orders of the month of November 2017.
I try something like that but it does not work:
SELECT COUNT(*)
FROM ps_orders o
WHERE YEAR(o.date_add) = YEAR(NOW() - INTERVAL 1 YEAR)
AND MONTH(o.date_add) = MONTH(NOW() - INTERVAL 1 MONTH)
Thank you for your help
You dont need to subtract the month. It should be MONTH(NOW()) to get the same month results from the previous year.
SELECT COUNT(*)
FROM ps_orders o
WHERE YEAR(o.date_add) = YEAR(NOW() - INTERVAL 1 YEAR)
AND MONTH(o.date_add) = MONTH(NOW()) -- same as current month
I would recommend doing this with date ranges:
SELECT COUNT(*)
FROM ps_orders o
WHERE o.date_add >= (curdate() - interval (day - 1) day) - interval 12 month AND
o.date_add >= (curdate() - interval (day - 1) day) - interval 11 month ;
When you use functions such as YEAR() and MONTH() the optimizer will not take full advantage of an available index on date_add. However, this version can use an appropriate index.
I want to know how many new users we have last month, and how many of them have turned into buyers while I can not figure it out smoothly.the following is what I coded.
SELECT COUNT(DISTINCT(PRODUCT_ID))
FROM ORDER_TABLE AS O
INNER JOIN CUSTOMER_TABLE AS C
ON O.CUSTOMER_ID=C.CUSTOMER_ID
WHERE DATEDIFF(MONTH,ORDER_DATE,GETDATE())<=1
And there is another question which has confused me a lot: Which category have the highest YEAR BY YEAR growth in terms of revenue in 2016?
This should do it...
SELECT COUNT(Customer_ID)
FROM Customer_Table
WHERE Customer_ID IN (
SELECT Customer_ID
FROM Order_Table
)
AND DATEDIFF(MONTH, First_Visit, GETDATE()) <= 1
Guessing ...
This gives a list of the new users last month.
SELECT Customer_ID, Country, Gender
FROM Customer_Table
WHERE First_Visit >= (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 2 MONTH
AND First_Visit < (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 1 MONTH
That date range, given that today is 2017-08-14, looks like this after all the date arithmetic. That means "the calendar month immediately preceding this day."
WHERE First_Visit >= '2017-07-01'
AND First_Visit < '2017-08-01'
The Number of new visitors last month is a simple summary of that query.
SELECT COUNT(*)
FROM Customer_Table
WHERE First_Visit >= (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 2 MONTH
AND First_Visit < (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 1
Now, to elaborate a bit. How do we tell if a new user has purchased anything? We look in the order table. Something like this will do it.
SELECT C.Customer_ID, SUM(O.Order_Amount) Total_Order_Amount
FROM Customer_Table C
LEFT JOIN Order_Table O ON C.Customer_ID = O.Customeer_ID
WHERE First_Visit >= (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 2 MONTH
AND First_Visit < (LAST_DAY(CURDATE()) + INTERVAL 1 DAY) - INTERVAL 1 MONTH
GROUP BY C.Customer_ID
This gives you a list of new customers, with a column showing how much each has ordered. So a NULL or 0 in the Total_Order_Amount column means a new customer who has never ordered anything.
Pro tip:
Incomplete and vague requirements are definitely part of stupid professor tricks. But they are also part of the world of information technology. Often a big part of a assignment, or a contract, or a project, is taking ridiculously vague requirements like the ones you've been given and refining them into something useful.
i got a MySQL tbl, with some colums, where every 5 min. a new row is inserted with 3 values
1. Auto inc. curent Date Unix timestamp --> date
2. power consumption absolut --> wert01
3. Power Generation absolut --> wert02
To Show this Information in a Graph, for Exampl for weekly power consumption, i need to select the First and the last, which allready Works, but then have to Substract the last from the First and Show only tue result & the day of the werk.
SELECT
(SELECT wert01
FROM sml_splitt
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate()) DAY
ORDER BY date DESC LIMIT 1) AS 'last',
(SELECT wert01
FROM sml_splitt
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate()) DAY
ORDER BY date LIMIT 1) AS 'lirst
I am searching for some days to find a solution, but with no success.
Hopfuly, you could help me.
If you're happy with your query, then you can do the math by nesting it one more time like this: http://sqlfiddle.com/#!9/515ef/1
select t1.last, t1.first, t1.last - t1.first as result
from (
select (
select wert01
from sml_splitt
where dt >= curdate() - interval dayofweek(curdate()) + 6 day
and dt < curdate() - interval dayofweek(curdate()) day
order by dt desc limit 1
) as 'last',
(
select wert01
from sml_splitt
where dt >= curdate() - interval dayofweek(curdate()) + 6 day
and dt < curdate() - interval dayofweek(curdate()) day
order by dt limit 1
) as 'first'
) t1
;
If you really want to work with this data by week for reporting purposes, let me suggest a couple of views. The first will give you all of your distinct beginning of week dates:
create view v1 as
select date(dt) as week_begins
from sml_splitt
where dayofweek(dt) = 1
group by week_begins
The second view joins the first view with itself to give you a week beginning and week ending range:
create view v2 as
select t1.week_begins, coalesce(t2.week_begins,now()) as week_ends
from v1 t1
left join v1 t2
on t2.week_begins = t1.week_begins + interval 7 day
You can see the results here: http://sqlfiddle.com/#!9/a4d1b3/2. Notice that I'm using now() to get the current date and time if the week hasn't ended yet.
From there you can join your view with your original table and use min() and max() function with grouping to get the starting and ending 'wert' values and do any calculations on them that you like.
Here's an example: http://sqlfiddle.com/#!9/a4d1b3/6
select week_begins, week_ends,
min(wert01) as start_wert01,
max(wert01) as end_wert01,
max(wert01) - min(wert01) as power_consumed,
min(wert02) as start_wert02,
max(wert02) as end_wert02,
max(wert02) - min(wert02) as power_generated,
(max(wert02) - min(wert02)) - (max(wert01) - min(wert01)) as net_generated
from v2
inner join sml_splitt
on sml_splitt.dt >= v2.week_begins
and sml_splitt.dt < v2.week_ends
group by week_begins
I hope that helps.
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/
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