MySQL Select entries from last 2 days of specific week / month - php

I got 2 columns, 'create_time' is when the account has been registered and 'last_play' is when the account has logged in the last time. I want to select accounts which have been registered in a specific week / month and have been active within the last 2 days of this specific week / month.
Here is how I select ALL entries of last week without considering last_play (works):
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW());
That's my current query for last week which doesn't work:
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND DATE(last_play) BETWEEN
ADDDATE(DATE(DATE_SUB(NOW(), INTERVAL 1 WEEK)),
INTERVAL 1 - DAYOFWEEK(DATE(NOW())) DAY)
AND DATE(NOW());

Basing on your first working query, you can use the MySQL function WEEKDAY to identify saturdays and sundays:
SELECT COUNT(id) FROM account.account
WHERE WEEKOFYEAR(create_time) = WEEKOFYEAR(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND WEEKOFYEAR(last_play) = WEEKOFYEAR(create_time) //last_play is in the same week as create_time
AND WEEKDAY(last_play) IN (5,6); //wekkday is saturday or sunday
This gives you entries which were active on the saturday or sunday in the same week they registered.
EDIT: For months, you basically do the same thing, but replace WEEKOFYEAR by MONTH and WEEKDAY by DAYOFMONTH. The last two days of a given month you can find manually by checing for all possible cases:
SELECT COUNT(id) FROM account.account
WHERE MONTH(create_time) = MONTH(NOW()) - 1
AND YEAR(create_time) = YEAR(NOW())
AND MONTH(last_play) = MONTH(create_time) //last_play is in the same MONTH as create_time
AND
(DAYOFMONTH(last_play) IN (30,31) AND MONTH(last_play) IN (1,3,5,7,8,10,12)
OR DAYOFMONTH(last_play) IN (29,30) AND MONTH(last_play) IN (4,6,9,11)
OR DAYOFMONTH(last_play) IN (27,28) AND MONTH(last_play) IN (2))
Never mind a leap year ;-). Or incorporate it again manually by yourself.

Related

How to pull data from database table for previous month only

I want to show records for previous month only, excluding this month's dates.For example, today is February 5th and I want to show records for January 1st to 31st
i have a table- tbl_order_details where I need to fetch all order records by current month and previous month respectively. the column name for date type is orderDate this is what I an doing for fetching rows for current month till date:
SELECT COUNT(1)
FROM tbl_order_details
where merchantCode= '$user_code'
AND MONTH(orderDate) = MONTH(CURRENT_DATE())
AND YEAR(orderDate) = YEAR(CURRENT_DATE())
But I cant figure out how do I show records for january that does not include any records from February
SELECT * FROM tbl_order_details
WHERE YEAR(orderDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(orderDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
For writing a PHP code, you can get the Month and Year from PHP itself by using the strtotime function depending upon the input your table takes and then formatting it in your sql query. For eg.:
<?php
$month = date("M", strtotime("previous month"));
$year = date("Y", strtotime("this year"));
$query_get = 'SELECT COUNT(1) FROM tbl_order_details where merchantCode= {$user_code} AND MONTH(orderDate) = {$month} AND YEAR(orderDate) = {$year}'
?>
And further pass $query_get to your DB query to fetch the required result. Or else, you can straight push the following query as #Rohit suggested above.
<?php
$query_get = 'SELECT * FROM tbl_order_details WHERE YEAR(orderDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(orderDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)'
?>
Avoid using DATE (), MONTH (), DAY (), YEAR (), SUBSTR (), LEFT (), RIGHT (), LIKE when mentioning columns in WHERE or JOIN'S because you no longer use the indexes that exist in the columns mentioned. Ex: WHERE YEAR(orderDate) = ... Avoid doing this for the reasons stated above.
I suggest use as follows ...
If your "orderDate" column is of type date, do as follows:
SELECT COUNT(1)
FROM tbl_order_details
where merchantCode= '$user_code'
AND orderDate BETWEEN DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY)
AND LAST_DAY(DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY));
Will return the first day of the previous month
DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY)
Returns the last day of the previous month
LAST_DAY(DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY))

MYSQL Last month Query is not returning first 9 days

I am querying records from the last calendar month. As it is February, it should return all the records that were added on January this year.
My Query:
`SELECT * FROM table_name WHERE date >=
DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1
DAY) AND date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1
MONTH)), INTERVAL 0 DAY) AND campaign = '$campaign' ORDER BY date
ASC`
It returns some records but skips the first 9 days. It starts showing records from 10th of the previous month. What am I missing here?
check your date field type and make sure you have not mistaken it with varchar.
SELECT * FROM table_name WHERE
(MONTH(date) = (MONTH(NOW()) - 1) AND YEAR(date) = YEAR(NOW()))
OR
(MONTH(date) = 12 AND MONTH(NOW())=1 AND YEAR(date) = (YEAR(NOW()) - 1) AND campaign = '$campaign' ORDER BY date
ASC`
Try To Get Data in step by step like,
First, you should try below query.
SELECT Date, DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AS StartDate, DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY) AS EndDate FROM MyTable
Second, If First Step give right date then get your data by directly writing your date rather than DATE_ADD function in where clause.
Third, If These will Give you write DATA then try to fetch data using DATE_ADD function.
Replay If you will get solution.
SELECT * FROM table_name WHERE date between DATE_SUB(DATE_SUB(CURRENT_DATE,INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY),INTERVAL 1 MONTH) AND DATE_SUB(DATE_SUB(CURRENT_DATE,INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY),INTERVAL 1 DAY) AND campaign = '$campaign' ORDER BY date ASC

Puling out data from the table from last week

$qry = "SELECT * FROM school WHERE WEEKOFYEAR(date) = WEEKOFYEAR(NOW()) ";
This query that i have currently in my code is getting me data from the current week starting from Monday. How can i get data from the table from last week or the week before. I have tried changing now to last week or currentweek.
any ideas is it possible to use weekofyear(()) and tweak it
You can do some date shift right in mysql, replace NOW() with
NOW() - INTERVAL 1 WEEK
there is also date_sub for subtracting
date_sub(NOW(),INTERVAL 1 WEEK)
Try this.
$qry = "SELECT * FROM school WHERE studId = $sessionId AND studentId = $student
AND date >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND date < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY"

Mysql Count Week Total of Current Month

I want to COUNT my data week by week current month.
For example;
Today is 25th of June.
We are on the last week of this month. So must be the 4th week of this month.
Week Total = 3125
Week Total = 7542
Week Total = 4565
Week Total = 1111 (Current week).
When july starts, we will get only first week. (Let's pretend we are in the 3rd day of july)
Week Total = 700
Any idea?
I did this for day of weeks but didn't get it work with the month.
Week example:
SELECT COUNT(id) as day_total, DATE(`date`) as week_day
FROM edp_orders
WHERE DATE(`date`) > DATE(CURDATE()) - INTERVAL 1 WEEK
GROUP BY DATE(`date`);
SELECT yearweek(`date`),
#n := #n + 1 as week_number,
COUNT(id) as week_total
FROM edp_orders
CROSS JOIN (select #num := 0) n
WHERE year(`date`) = year(curdate())
AND month(`date`) = month(curdate())
GROUP BY yearweek(`date`)

Every specific weekday, sql and php

Currently, I got this:
SELECT `deals`.*, deals_bookings.date AS 'b_date', deals_bookings.id AS 'book_id'
FROM `deals_bookings`
INNER JOIN deals ON (deals.ID = deals_bookings.deal_id)
INNER JOIN users ON (users.id = deals.partner_id)
INNER JOIN deals_bookings_times ON (deals_bookings_times.book_id = deals_bookings.id)
WHERE 1 AND deals_bookings.date = CURDATE() AND users.company_type = 'restaurant'
This grabs deals, that has a booked date for today (CURDATE()).
Now I have added a column: deals_bookings.everyWeekDay
The plan for that column is to store week number -> between 1-7 where 1 is monday (first day in week) and 7 is sunday.
Is it possible by pure mysql query to select all deals that has either deals_bookings.date = CURDATE() OR if deals_bookings.everyWeekDay = todays week number ?
YOu want to use
deals_bookings.everyWeekDay = WEEKDAY(NOW())
But WEEKDAY returns Monday - 0, Sunday - 6; so we have to add 1
Combining the condition
WHERE (`deals_bookings`.`date` = CURDATE() OR `deals_bookings`.`everyWeekDay` = WEEKDAY(NOW()) + 1 ) AND `users`.`company_type` = 'restaurant'

Categories