mysql从子查询中获取列的总和,同时仍返回所有记录

时间:2018-01-28 05:20:29

标签: mysql subquery

我正在尝试返回一组记录,但也希望包含总和。

SELECT track_date AS label, track_count AS value
FROM trackers
INNER JOIN (
SELECT tracker_details.track_id, COUNT(track_id) AS track_count, DATE(date_created) AS track_date
    FROM tracker_details
    WHERE (DATE(date_created) >= '2018-01-21' 
    AND DATE(date_created) <= '2018-01-27') 
    AND client_id = 1
    GROUP BY DATE(date_created)) as tracker_details 
ON trackers.track_id = tracker_details.track_id
WHERE trackers.client_id = 1 
ORDER BY DATE(track_date)

目前没有总和的回报:

label       value
2018-01-21  9
2018-01-22  2
2018-01-26  3
2018-01-27  2

在选择中添加SUM:

SELECT track_date AS label, track_count as value, SUM(track_count) as total

它正在回归:

label   value   total
2018-01-22  2   16

我想要实现的目标是:

label       value total
2018-01-21  9     16
2018-01-22  2     16
2018-01-26  3     16
2018-01-27  2     16
我错过了什么? 任何帮助表示赞赏。

提前谢谢。

EDIT 我能够通过添加WITH ROLLUP来解决这个问题。 &#39; GROUP BY DATE(date_created)WITH ROLLUP&#39;

这创建了一个额外的行:

label       value
null        21
2018-01-15  2
2018-01-16  5
2018-01-17  1
2018-01-20  4
2018-01-21  9

1 个答案:

答案 0 :(得分:0)

不幸的是,laravel和其他聚合函数只返回一行。您需要在执行查询后以编程方式添加列,或者将sum添加为子查询,如下所示:

<?php

require_once 'DBOperations.php';

class Functions{

private $db;

public function __construct() {
  $this -> db = new DBOperations();
}

public function searchPosts($rawLocation){
  $db = $this -> db;
  $locationArr = explode(",", $rawLocation);
  $formattedCity = $locationArr[0];
  $formattedState = $locationArr[1];
  echo 'String parameters for getLocationID are: 
'.$formattedCity.','.$formattedState.'.';
  if (checkLocationExists($formattedCity, $formattedState)){
      $locationID = $db -> getLocationID($formattedCity,
$formattedState);
      echo $locationID.'...is the locationId returned by "$db
>getLocationID()"';
      $response = $db -> getPostsByLocation($locationID);
      return json_encode($response);
  }else {
    $response['message'] = 'Location not in database, select one from
the AutoComplete drop down.';
    json_encode($response);
  }
}
public function checkLocationExists($city, $state) {
  $db = $this -> db;
  if ($db -> checkCity($city) && $db -> checkState($state) ) {
    return true;
  } else {
    return false;
    }
}