How DO I fetch last Week and current week - mysql

How do I fetch last week data from monday time (00:00:01) and end on sunday time (23:59:59)...
same as this current week from monday time (00:00:01) and end on sunday time (23:59:59)
WHat I tried!
$query = "SELECT users.name,count(*) as count,
campaign.campaign_name,
campaign.payout_cost*count(*) as totalPrice
FROM users
JOIN transactions on users.uid=transactions.uid
JOIN campaign on campaign.campaign_id_id=transactions.campaign_id
WHERE uid=$uid
AND `date` >= DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())+6 DAY)
AND `date` < DATE_SUB(DATE(NOW()), INTERVAL DAYOFWEEK(NOW())-1 DAY)
GROUP BY campaign.campaign_name_name ";

You are on the right track by avoiding functions like week() on the column -- that just messes up the optimizer. On the other hand, the uid parameter should be passed as a parameter rather than munging the query string.
You want to use the weekday() function because you want weeks to start on a Monday. Just some arcaneness of MySQL: weekday() returns 0 for Monday whereas dayofweek() returns 2 for Monday.
So, the logic for the current week would be:
date >= curdate() - interval weekday(curdate()) day and
date < curdate() + interval 7 - weekday(curdate()) day
For last week, this would be:
date >= curdate() - interval 7 + weekday(curdate()) day and
date < curdate() + interval - weekday(curdate()) day
Notes that curdate() (or current_date) returns the current date with no time component, so no date() is required.

Couple of ways to do it...
select data from tableName
where date between date_sub(now(),INTERVAL 1 WEEK) and now();
select data FROM tableName
wherdate >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY

You can use WEEK() function, which returns the week number for a given date, by adding
AND WEEK(date-INTERVAL 1 DAY) = WEEK(NOW()) - 1 to get current week's data starting from monday upto sunday,
and
AND WEEK(date-INTERVAL 1 DAY) = WEEK(NOW()) - 2 for the previous week's data
into the WHERE condition after WHERE uid=$uid
such as
$query = "SELECT c.campaign_name,
COUNT(*) as total_count,
SUM(c.payout_cost) as total_payout
FROM transactions t
JOIN campaign c
ON c.campaign_id = t.campaign_id
WHERE uid = $uid
AND WEEK(date - INTERVAL 1 DAY) = WEEK(NOW()) - 1
GROUP BY c.campaign_name ";
and replace WEEK(NOW()) - 1 with WEEK(NOW()) - 2, also
Demo

Related

Get the data of the last week from (Monday to Sunday)

I would like to get the data from the last week. A week is Monday to Sunday.
I made this query :
sql = 'SELECT COUNT(*) ' \
'FROM panelname ' \
'WHERE year(date) = year(now()) ' \
'AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() '
cursor.execute(sql)
test = cursor.fetchall()
print(test)
The problem with AND date BETWEEN date_sub(now(),INTERVAL 1 WEEK) AND now() is that it takes the data from the past 7 days. If I am Tuesday of the current week and I run it, I will get the data from last week's Tuesday up until this week's Tuesday, which is not what I want. It should give the data from last Monday down to last Sunday.
I also precise that it should not use the DATEADD function, because I don't have the admin rights to use it.
For example : I run the query today, it doesn't matter which day we are, and I get the last week of data (Monday to Sunday).
Thank you.
You must first get the most recent Monday and use it as a reference point to calculate the 5 previous weeks:
SELECT COUNT(*)
FROM panelname
WHERE date >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) day - INTERVAL 5 week
AND date < CURDATE() - INTERVAL WEEKDAY(CURDATE()) day
UPDATE
To get the aggregated count per each week you need to group by week:
SELECT WEEKOFYEAR(date),COUNT(*)
FROM panelname
WHERE date >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) day - INTERVAL 5 week
AND date < CURDATE() - INTERVAL WEEKDAY(CURDATE()) day
GROUP BY WEEKOFYEAR(date)

mysql query how to show each day's total cash sale for the current week

I have the following mysql query which shows the each day's total cash sale for the current week.
SELECT
sum(Price) as totalprice,
WEEKDAY(CreatedOn) as dayno,
DATE(CreatedOn) as CreatedOn,
AgentID
FROM records
WHERE CreatedOn BETWEEN (CURDATE()-WEEKDAY(CURDATE())) AND CURDATE()
GROUP BY DATE(CreatedOn)
When I run the query it looks like this:
There are records on 30th November(today's date). So,
day 0 (Monday) no cash sale
day 1 (Tuesday) $5049
day 2 (Wednsday) $99
Nothing is displayed for day 3 (Thursday/today). I cannot figure out the reason there are definitely record in the database but cannot get them to be displayed. I would appreciate any help.
CURDATE() is today's date but at 00:00:00+0000000
"push up" the higher date by 1 day and avoid using between for date/time ranges:
WHERE CreatedOn >= date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
AND CreatedOn < date_add(CURDATE(), INTERVAL 1 DAY)
select date_sub(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY)
, date_add(CURDATE(), INTERVAL 1 DAY)
The condition in the query currently specifies on or before midnight today, so any rows for today after midnight are going to be excluded.
I think you are intending to specify CreatedOn before midnight of the following day.
I also suggest you don't subtract an integer value from a date/datetime, and instead use the INTERVAL syntax
WHERE CreatedOn >= CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
AND CreatedOn < CURDATE() + INTERVAL 1 DAY
To test those expressions before we include them in a query, we can run a SELECT statement:
SELECT CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY
, CURDATE() + INTERVAL 1 DAY
and verify that those expressions are returning what we expect, the values we want to use. For testing, we can replace CURDATE() with a date value to test the return for days other than today.

comparing dates by month and year in mysql

I have a table containing data about events and festivals with following columns recording their start and end dates.
Start_Date
End_Date
date format is in YYYY-MM-DD. I need to fetch event details with the following condition.
Need to fetch all events which start with a current month and there end dates can be anything say currentDate+next30days.
I am clear about end date concept. but not sure how I can fetch data whose start dates are in a current month.
For this, I need to compare current year and current month against the Start_Date column in my database.
Can anyone help me to point out as how I can do that?
select * from your_table
where year(Start_Date) = year(curdate())
and month(Start_Date) = month(curdate())
and end_date <= curdate() + interval 30 day
I don't like either of the other two answers, because they do not let the optimizer use an index on start_date. For that, the functions need to be on the current date side.
So, I would go for:
where start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
All the date functions are on curdate(), which does not affect the ability of MySQL to use an index in this case.
You can also include the condition on end_date:
where (start_date >= date_add(curdate(), interval 1 - day(curdate()) day) and
start_date < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 1 month)
) and
end_date <= date_add(curdate(), interval 30 day)
This can still take advantage of an index.
DateTime functions are your friends:
SELECT
*
FROM
`event`
WHERE
(MONTH(NOW()) = MONTH(`Start_Date`))
AND
(`End_Date` <= (NOW() + INTERVAL 30 DAY))
AND
(YEAR(NOW()) = YEAR(`Start_Date`))
Comparing the year and month separately feels messy. I like to contain it in one line. I doubt it will make a noticeable difference in performance, so its purely personal preference.
select * from your_table
where LAST_DAY(Start_Date) = LAST_DAY(curdate())
and end_date <= curdate() + interval 30 day
So all I'm doing is using the last_day function to check the last day of the month of each date and then comparing this common denominator. You could also use
where DATE_FORMAT(Start_Date ,'%Y-%m-01') = DATE_FORMAT(curdate(),'%Y-%m-01')

MySQL query to get data for the last week

I want to run a MYSQL query to get data for the previous week. The datatype for the date column is DATETIME. Could anyone suggest?
SELECT *
FROM calendar
WHERE dt BETWEEN CURDATE()-INTERVAL 1 WEEK AND CURDATE();
Here is an another version:
SELECT * FROM table WHERE
YEARWEEK(`date`, 1) = YEARWEEK( CURDATE() - INTERVAL 1 WEEK, 1)
SELECT id FROM tbl
WHERE date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
Here is the solution I find most reliable for getting data between the previus monday to the current monday. (That is what most people mean when the say past week, but not all, and that reflect in mysql).
SELECT
*
FROM
table
WHERE
date BETWEEN
(CURDATE() - INTERVAL 1 DAY) + INTERVAL -1 WEEK - INTERVAL WEEKDAY((CURDATE() - INTERVAL 1 DAY)) DAY
and
(CURDATE() - INTERVAL 1 DAY) + INTERVAL 0 WEEK - INTERVAL WEEKDAY((CURDATE() - INTERVAL 1 DAY)) DAY
It's also easy to change it for another week intervall
Make variable for current datetime - 1 week and make this query:
SELECT * FROM table WHERE date > $datatime

MySQL Select Dates within Calendar week

I want to select all data from a table where a last_update field is 'this week'. So between the previous Sunday, and the upcoming Saturday.
I found this answer that finds dates LAST Week, but I can't quite figure out how to tailor it for what I need, which is this calendar week.
SELECT * FROM items
WHERE last_update >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND last_update < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
I think I found the answer on this one:
SELECT * FROM items
WHERE last_update >= curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
AND last_update <= curdate() + INTERVAL 7 DAY - DAYOFWEEK(curdate())