PHP Mysql GET Last month and current month data - php

I want to retrieve m last month data and current month data
my query works correctly as
last month data calculate 1 month from current date. But i want my data calculate as calander month not from my current date.
like
my current date is 2014-07-23
now my calculation return data by calculating month from my current date.
but I want to get based on calendar jan,feb,march range.
my current query of last month
SELECT (100*AVG((m.carbs)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_carbs,(100*AVG((m.fat)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_fat,(100*AVG((m.protein)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_protein
FROM `meal` AS m,`user_history` as u where u.meal_id=m.id and u.user_id=$user_id and date(FROM_UNIXTIME(u.create)) BETWEEN SUBDATE(CURDATE(), INTERVAL 1 MONTH) AND NOW()
my current query of this month
SELECT (100*AVG((m.carbs)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_carbs,(100*AVG((m.fat)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_fat,(100*AVG((m.protein)/((m.carbs)+(m.fat)+(m.protein)))) AS Percantage_protein
FROM `meal` AS m,`user_history` as u where u.meal_id=m.id and u.user_id=$user_id and YEARWEEK(date(FROM_UNIXTIME(u.create))) = YEARWEEK(CURRENT_DATE)

Last month
year(date(FROM_UNIXTIME(u.create))) = year(CURDATE() - INTERVAL 1 MONTH)
and month(date(FROM_UNIXTIME(u.create))) = month(CURDATE() - INTERVAL 1 MONTH)
THis month
year(date(FROM_UNIXTIME(u.create))) = year(CURDATE())
and month(date(FROM_UNIXTIME(u.create))) = month(CURDATE())

Related

SELECT count(*) from where date(week number) equal to current week number

I am using this to query from my table:
$res = $link -> query("SELECT count(*) FROM sales WHERE status='OK'") or die($mysqli->error);
$num_rows = mysqli_fetch_row($res)[0];
$numberOfSales = $num_rows;
In table sales I also have a column named date datetime.
I want it to only returns the number of rows where date is the same as the current week number. So if the date column cell has value 2020-08-03 16:25:26, that converted to week number is 32. I have been looking at strftime("%V",, but not sure how to proceed. Any tips?
Consider and index-friendly expression such as:
select count(*)
from sales
where
status='OK'
and datetime >= current_date - interval weekday(current_date) day
Expression current_date - interval weekday(current_date) day dynamically computes the date that corresponds to the first day of the current week (starting on Monday).
If you may have dates in the future, then you can add an upper limit:
where
status='OK'
and datetime >= current_date - interval weekday(current_date) day
and datetime < current_date + interval (7 - weekday(current_date)) day

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))

SUM multiple date ranges in mysql query

I have a MySql table 'Products' with three columns:
Date | Product | Qty
My aim is to SUM the qty of each product for every week.
Getting the SUM between two given dates would be easy:
SELECT SUM(qty) FROM products WHERE date >= '2010-01-01' AND date < '2011-01-1'
I can generate a list of weeks in Php using something like:
$today = date('Y-m-d', strtotime('last week Monday'));
$future = date('Y-m-d', strtotime('+90 days'));
$period = new DatePeriod(
new DateTime($today),
new DateInterval('P7D'),
new DateTime($future)
);
foreach ($period as $key => $value) {
$dates .= $value->format('Y-m-d');
}
Is there a MySql query that would work to Group By and SUM by dates? Or would I be better off looping through in Php?
You can use Year() and Week() functions in MySQL, to get the year and week number for a given date. Week() function will return week number from 0 to 53. So, you will be needed to use Year() function alongwith, if you have data spanning over multiple years.
But then, you will be more interested in knowing the start date and end date for the concerned week. This is where we can use a very interesting function DayOfWeek(). It returns the weekday index for a given date (1 = Sunday, 2 = Monday, …, 7 = Saturday)
We can use Date_Add() function using the weekday index value and the actual date value, to determine the starting week date and ending week date for a given date.
Try the following (if the Week starts on Sunday) :
SELECT
DATE_ADD(`date`, INTERVAL(1 - DAYOFWEEK(`date`)) DAY) AS week_start_date,
DATE_ADD(`date`, INTERVAL(7 - DAYOFWEEK(`date`)) DAY) AS week_end_date,
SUM(qty)
FROM
products
GROUP BY week_start_date, week_end_date
If the week starts on Monday, another handy function is WeekDay(). It returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
Try the following (if the Week starts on Monday) :
SELECT
DATE_ADD(`date`, INTERVAL(0 - WEEKDAY(`date`)) DAY) AS week_start_date,
DATE_ADD(`date`, INTERVAL(6 - WEEKDAY(`date`)) DAY) AS week_end_date,
SUM(qty)
FROM
products
GROUP BY week_start_date, week_end_date
You can achieve that with a group by like
GROUP BY week(date)
GROUP BY so do
SELECT SUM(qty) FROM products GROUP BY WEEK(date);

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

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.

MySQL first day and last day of current and previous month from date (no timestamp)

I hope following query will give you the idea what I am looking for-
SELECT SUM(t1.hours) AS totalhours FROM
(
SELECT (time_to_sec(timediff(time_out, time_in)) / 3600) AS hours FROM bb_work_log
WHERE user_id = 6 AND (working_date BETWEEN '2014-04-01' AND '2014-04-31')
) AS t1
In my query, you can see the working_date which I given here manually. But, I would not like to do it manually. I would like to pick first day and last day of current month dynamically.
First day of Previous Month
select last_day(curdate() - interval 2 month) + interval 1 day
Last day of Previous Month
select last_day(curdate() - interval 1 month)
First day of Current Month
select last_day(curdate() - interval 1 month) + interval 1 day
Last day of Current Month
select last_day(curdate())
You can use LAST_DAY(NOW() - INTERVAL 1 MONTH) + INTERVAL 1 DAY,which will subtract one month from now and by by adding 1 day in LAST_DAY of previous month will give you the first day of current month
SELECT SUM(t1.hours) AS totalhours FROM
(
SELECT (time_to_sec(timediff(time_out, time_in)) / 3600) AS hours FROM bb_work_log
WHERE user_id = 6
AND (working_date BETWEEN LAST_DAY(NOW() - INTERVAL 1 MONTH)
AND LAST_DAY(NOW()))
) AS t1
LAST_DAY(NOW() - INTERVAL 1 MONTH) this will give you the last day of
previous month
First/Last day of Month Fiddle Demo
You can achieve it these ways ----
/* Current month*/
SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))-1 DAY),CONCAT(LAST_DAY(NOW()),' 23:59:59');
SELECT LAST_DAY(CURDATE()) - INTERVAL DAY(LAST_DAY(CURDATE()))-1 DAY ,CONCAT(LAST_DAY(NOW()),' 23:59:59');
/* previous month*/
SELECT DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH,'%Y-%m-01 00:00:00'),DATE_FORMAT(LAST_DAY(CURDATE()-INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59');
-- first day of previous month
set #start_date = date_format(NOW() - INTERVAL 1 MONTH, '%Y-%m-01');
-- last day of previous month
set #end_date = date_format(NOW() , '%Y-%m-01') - INTERVAL 1 day;
select #start_date ,#end_date ;
-- first day of current month
set #start_date = date_format(NOW(), '%Y-%m-01');
-- last dat of current month
set #end_date = date_format(NOW() + INTERVAL 1 MONTH, '%Y-%m-01') - INTERVAL 1 day;
select #start_date ,#end_date ;

Categories