get sum of values from mysql table by month starting current month - php

Hi i currently have two tables, one has daily entries and other gets the total of those and stores monthly values.
I'm able to get totals of each month and year with below query, but what i'd like to do is only get the months where month is greater than and equal to current month. btw date column is in date format (yyyy-mm-dd)
$revbyMonth = $conn->prepare("SELECT EXTRACT(MONTH FROM date) as month, EXTRACT(YEAR FROM date) as year, SUM(rev) as total FROM {$tempName} GROUP BY year, month");

You want to add a where clause immediately after the from clause. I think this will work for you. If the date has no time component:
where date > date_sub(curdate(), interval day(curdate()) day)
The expression date_sub(curdate(), interval day(curdate()) day) gets the last day of the previous month. If the dates have a time component:
where date >= date_sub(curdate(), interval day(curdate()) - 1 day)
should work.
Note: this is better than other methods that process date using functions, such as:
where year(date) > year(curdate()) or
(year(date) = year(curdate()) and month(date) >= month(curdate()) )
The use of the functions prevents MySQL from using an index on the date column.

Related

Ranking query from the last x months

I want to get all records from the last x months from my MySQL server. Using 2 months for example(Not from last 2 months, like last 60 days, but from the entire past month and so on. If actual month is april, I want all records from february and march).
I've tried some queries and the last one is
SELECT id FROM ranking WHERE (end_date BETWEEN DATE_FORMAT(NOW(), '%Y-%m-01') AND DATE_FORMAT(LAST_DAY(NOW() - INTERVAL 2 MONTH), '%Y-%m-%d'))
"end_date" is my date column which is a DATE column "2017-04-07".
That query above just returns nothing and I cant figure out where is the error.
Try this:
SELECT id
FROM ranking
WHERE end_date BETWEEN
DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 3 MONTH)) INTERVAL 1 DAY)
AND LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH));
It calculates dates as like this:
For start date in range, it subtracts 3 months from current date, gets the last day of that month and adds a day in it to get the first day of next month (1st February in our case)
For end date, it subtracts one month from current date and gets the last day of that month (31st March in our case)
Try without convert it to string, And BETWEEN requires min date first.
SELECT id
FROM ranking
WHERE end_date BETWEEN LAST_DAY(CAST(NOW() as date) - INTERVAL 2 MONTH
AND CAST(NOW() as date)

Count current month from Database

i would like to count the date from the database where the month is now.
my code goes like
$sql="SELECT count(date) FROM tbl_upcoming where
date=MONTH(NOW())";
if ($results=mysqli_query($conn,$sql)){
$datecount=mysqli_num_rows($results);
}
for example: '2017-3-20', '2017-3-4', '2017-1-3', it will return 2.
Try something like this:
SELECT date, count(1) FROM tbl_upcoming where
MONTH(date)=MONTH(NOW()) and YEAR(date) = YEAR(NOW()) GROUP BY date
You were almost there:
SELECT count(*) FROM tbl_upcoming WHERE MONTH(the_date)=MONTH(NOW())";
The approach of MONTH(NOW()) is good, this will return you the current month.
However you were comparing the current month with a whole date, which can't work. You also have to apply the MONTH() function to your date to compare months with months
You should check like this,
month can be from past year or next year also,
select count(*) as cnt from tbl_upcoming
where MONTH(date) = MONTH(CURRENT_DATE) and YEAR(date) = YEAR(CURRENT_DATE);
I hope this will help.
You want to know how many rows are in the current month?
SELECT COUNT(*)
FROM tbl_upcoming
WHERE `date` >= CURDATE() - INTERVAL DAY(CURDATE())-1 DAY;
Notes:
In most situations, say simply COUNT(*).
CURDATE() is midnight this morning, hence easier to deal with for your query.
CURDATE() - INTERVAL DAY(CURDATE())-1 DAY gives you the DATE of the first of this month.
The formulation avoids all hiccups with various datatypes: DATE, DATETIME, DATETIME(6), TIMESTAMP, etc.
The next note handles leapdays, end of year, also.
If you have dates reaching into future months, then
add
AND `date` < CURDATE() - INTERVAL DAY(CURDATE())-1 DAY
+ INTERVAL 1 MONTH;

Display only future database records with MySQL

I am trying to display only records two weeks in advance from the current date onwards. starttime is stored as a datetime data type in the database.
I have this,
SELECT id, date_format(starttime, '%d-%m-%Y %H:%i') AS formatted_start, date_format(starttime, '%Y-%m-%d') AS formatted_date,
date_format(endtime, ' %H:%i') AS formatted_end
FROM timedates WHERE user_id = 1 AND `status`='' AND YEARWEEK(formatted_date, 0) IN (YEARWEEK(NOW(), 0),
YEARWEEK(DATE_ADD(NOW(), INTERVAL 2 WEEK), 0))
But I am getting a syntax error YEARWEEK(formatted_date, 0) IN (YEARWEEK(NOW(), 0) AND YEARWEEK(DATE_ADD(NOW()
Could anyone tell me what's wrong with it?
It seems MySQL does not support calculated column in the where clause:
try
SELECT id, date_format(starttime, '%d-%m-%Y %H:%i') AS formatted_start,
date_format(starttime, '%Y-%m-%d') AS formatted_date,
date_format(endtime, ' %H:%i') AS formatted_end
FROM timedates
WHERE user_id = 1 AND `status`='' AND
YEARWEEK(starttime, 0) IN (
YEARWEEK(DATE_ADD(NOW(), INTERVAL 1 WEEK), 0),
YEARWEEK(DATE_ADD(NOW(), INTERVAL 2 WEEK), 0))
use starttime instead of formatted_date
As I said, I see no reason to use YEARWEEK function. You need start date set to today which is CURDATE() and plus 2 weeks period which is DATE_ADD(CURDATE(), INTERVAL 2 WEEK) and then we just check if starttime between those 2 dates.
SELECT id, date_format(starttime, '%d-%m-%Y %H:%i') AS formatted_start,
date_format(starttime, '%Y-%m-%d') AS formatted_date,
date_format(endtime, ' %H:%i') AS formatted_end
FROM timedates
WHERE user_id = 1
AND `status`=''
AND DATE(starttime) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 2 WEEK)
How do you define "two weeks in advance"? Our normal inclination, is to think "within two weeks", which would be to simply before 14 days from now.
WHERE starttime >= NOW()
AND starttime < NOW() + INTERVAL 14 DAY
But the original query is using YEARWEEK function, and the behavior with that is a bit different.
If today is Thursday, May 21, 1015. What is the range of dates that starttime should fall into?
For datetimes right now or in the future, we can just do:
WHERE starttime >= NOW()
(We can do just a > rather than >= if we want to exclude startime values that are an exact match for NOW().
The question is, the bit about "two weeks in advance". Adding 14 days, or 2 weeks, would get us up to Thursday, June 4, 2015. It looks like you might also want to include Friday and Saturday, June 5th and 6th. (Up until Sunday, June th.)
We can use an expression to return "Sunday on or following 14 days from today"
If it's a Sunday, we just use that date. (For convenience, we think of that as adding 0 days). If it's Saturday, we need to add 1 day. If it's a Friday, add 2 days, ... Monday, add 6 days.
Conveniently, the expression 6 - WEEKDAY(NOW()) gives us the number of days we need to add to today's date to get to the next Sunday.
Reference: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_weekday
We probably want to lop the time off at midnight, we can use the DATE() function to do that.
-- startime values on or after now and before midnight
-- of the first sunday on or after the date two weeks from now
WHERE starttime >= NOW()
AND starttime < DATE(NOW()) + INTERVAL 14+6-WEEKDAY(NOW()) DAY
It's much easier to read and understand what the query is doing when we reference bare columns from the table on one side, and do the gyration and manipulation on the other side. It's also easier to test. And, maybe more importantly, it allows MySQL to make effective use of an "range scan" operation on a suitable index, rather than having to evaluate a function on every row in the table.
If today is '2015-05-21', and what you meant by "two weeks in advance" was up until the second Sunday from now (Sunday, May 31, 2015... 1 week and 3 days from now) just replace the 14 with 7.
Again, it really depends on how you define "two weeks in advance", how you determine what that ending date boundary is. Once you can define that, you can write an expression that returns the value, and just compare to value stored in the starttime column.

Fetch rows only from specific date in mySQL

I am trying to fetch rows only from specific date (like today, yesterday or 2 days ago) in mySQL. I have a column named "date" in my rows. (which includes dates like 1365053426).
$result=mysql_query("SELECT count(*) as total from track WHERE `date` >= CURRENT_DATE
AND `date` < CURRENT_DATE + INTERVAL 1 DAY");
I have tried this query, but it returns "0". What is the correct way to do that ?
how about using BETWEEN?
SELECT COUNT(*) as TotalCount
FROM Track
WHERE Date BETWEEN CURDATE() + INTERVAL -2 DAY AND CURDATE()
How about using datediff() function?
SELECT count(*) as total from track WHERE datediff(now(),date)=interval day
note: interval day could be declare from 0 -> up depends on what previous date you want to show

PHP MySQL - Select all where expiry date = todays date + 7 days

I am using PHPMyadmin and putting values in a database using PHP. I store the expiry date of products using a timestamp as follows,
FOR EXAMPLE:
2012-11-04
I want to select all where the expiry date is equal to todays date plus 8 days (such as the one above)
I also want to select all where expiry date is equal to todays date + 2 weeks in a seperate page if any one could help me out would be very grateful!
You can do that with a query like this:
SELECT * FROM table WHERE date = DATE_ADD(CURDATE(), INTERVAL 8 DAY)
You can use DATE_SUB for dates in the past.
Select all where the expiry date is equal to todays date plus 8 days
SELECT
*
FROM
products
WHERE
products.expiry_date >= DATE(now())
AND
products.expiry_date <= DATE_ADD(DATE(now()), INTERVAL 8 DAY)
Select all where the expiry date is equal to todays date plus 2 weeks
SELECT
*
FROM
products
WHERE
products.expiry_date >= DATE(now())
AND
products.expiry_date <= DATE_ADD(DATE(now()), INTERVAL 2 WEEK)
These docs will be helpful for you:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add

Categories