简体   繁体   中英

Find all data in date range then calculate total per month

I have a mysql table in which each record has a startDateTime and a finishDateTime . I want to be able to return the total time in each month.

My current query is this:

$dateRange = "BETWEEN '$startDate' AND '$finishDate'"; 

$sql = 
"SELECT 
    TIMESTAMPDIFF(MINUTE, StartDateTime, FinishDateTime) As Duration,
    StartDateTime As Start, FinishDateTime As Finish
FROM Entries
WHERE StartDateTime $dateRange AND FinishDateTime $dateRange";

Table Entries

| StartDateTime       | FinishDateTime |
| 2016-08-18 10:00:00 | 2016-08-18 11:00:00 |
| 2016-08-18 12:00:00 | 2016-08-18 14:00:00 |
| 2016-08-31 17:00:00 | 2016-09-01 09:00:00 |

Desired Output
| Month               | Duration       |
| Aug                 | 10             |
| Sept                | 9              |

which will return the duration of each record but not the total for each month. What do I need to add to or change in this query to get the required data?

Supposedly that every entry is started and finished in the same month try the following:

$sql = 
    "SELECT 
        SUM(TIMESTAMPDIFF(HOUR, StartDateTime, FinishDateTime)) As Duration
    FROM Entries
    WHERE 
        YEAR(StartDateTime) = YEAR(FinishDateTime) 
        AND MONTH(StartDateTime) = MONTH(FinishDateTime)
        AND StartDateTime $dateRange 
        AND FinishDateTime $dateRange
    GROUP BY MONTH(StartDateTime)";

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