如何从毫秒列中按月对MSQL数据库的结果分组?

时间:2019-04-14 19:01:32

标签: php mysql slim

我正在尝试使用SLIM框架从MSQL数据库获取基于月份的项目总数,当我显示数据时,我得到的结果是,但即使在同一个月份中也分开了。我的代码是

    $app->get('/view/test', function ($request, $response, array $args) {
      try {
    $con = $this->db;
    date_default_timezone_set('UTC+3h');
    $sql = "SELECT start_time,COUNT(*) as tt FROM parking_sessions GROUP 
     BY FROM_UNIXTIME(start_time/1000)";
    $result = null;
    $results = null;
    foreach ($con->query($sql) as $row) {

        $result['muda'] = date('M',($row['start_time']/1000));
        $result['total'] = $row['tt']; 
        $results[] =$result; 
        $total = count($results);
    }
    if ($result) {
        return $response->withJson(array('status' => 'true', 'date' => 
        $results, 'jumla' => $total), 200);
    } else {
        return $response->withJson(array('status' => 'Owner Not Found'), 
         422);
    }

} catch (\Exception $ex) {
    return $response->withJson(array('error' => $ex->getMessage()), 422);
}

});

它给了我以下结果

      "date": [
    {
        "month": "Feb",
        "total": "1"
    },
    {
        "month": "Mar",
        "total": "1"
    },
    {
        "month": "Apr",
        "total": "1"
    },
    {
        "month": "Apr",
        "total": "1"
    }
],

所有需要的结果如下所示

    "date": [
    {
        "month": "Feb",
        "total": "1"
    },
    {
        "month": "Mar",
        "total": "1"
    },
    {
        "month": "Apr",
        "total": "2"
    }
],

我的数据库看起来像

    id slot_id    customer_vehicle_id    start_time        end_time             check_out_time      status


    1    1              2                1553249524000     1554346841515            1553111000          1

    2    6              4                1554351619803     1553253124000            1553214094          0

    3    6              4                1555224715000     1553253124000            1553214094          0

    4    7              3                5086800000        1553253124000            1553214094          0

1 个答案:

答案 0 :(得分:0)

您无法使用unixtime对查询进行分组,因为您在unix时间中获得的每一秒和每分钟都是不同的。您需要将其转换为没有时间的日期。 从parking_sessions GROUP中选择tt作为start_time,COUNT(*)作为tt      截止日期(FROM_UNIXTIME(start_time / 1000)) 注意:日期将截断分钟,而您仅留下日期