查找日期范围内的所有数据,然后计算每月的总数

时间:2016-09-02 13:11:57

标签: mysql sql

我有一个mysql表,其中每条记录都有startDateTimefinishDateTime。我希望能够在每个月返回总时间。

我目前的疑问是:

$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";

表条目

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

将返回每条记录的持续时间,但不会返回每月的总数。我需要添加或更改此查询以获取所需数据?

1 个答案:

答案 0 :(得分:1)

据说每个条目都在同一个月开始并完成,请尝试以下方法:

$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)";