简体   繁体   中英

Getting the total number using the range of two dates in php mysql

I'll give you an example:

date - entries
03/05/2017 - 10
03/06/2017 - 5
03/07/2017 - 5
03/08/2017 - 10

I want the result to be 30

I want to add all the entries of all those in the range of the first and last dates using php and mysql but I have no idea how. Can someone please help me?

If the sample you showed us really represents all the records in the table, then the following should work:

SELECT SUM(entries) AS the_sum
FROM yourTable

If there is more data, but only want to sum over a certain date range, then you can restrict the sum using a WHERE clause:

SELECT SUM(entries) AS the_sum
FROM yourTable
WHERE STR_TO_DATE(date, '%m/%d/%Y') BETWEEN '2017-03-05' AND '2017-03-08'

Note that in the second query I had to resort to using STR_TO_DATE() because it appears that you are storing your dates as text in the format 03/05/2017 . Hence, we need to first convert this to a date type in order to compare it to other dates.

In general, you should try to avoid storing your date information as text, because it makes it difficult to work with such data in your database. Instead, use a date type to store this information ( date , datetime , timestamp ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM