查询计算MySQL数据库列中的值

时间:2016-09-15 22:11:11

标签: php mysql sql json

我有一个MySQL查询,它按月在我的数据库中添加所有ClientCostToDate行(类型为DECIMAL),并将数据作为JSON返回。

我的PHP脚本是:

//the sql query to be executed
$estimates_query = "SELECT DATE_FORMAT(CreatedDate, '%M %Y') AS CreatedMonth,
 SUM(ClientCostToDate) AS ClientCostsTotal,
 EXTRACT(YEAR_MONTH FROM CreatedDate) AS CreatedYearMonth
 FROM Estimates
 WHERE CreatedDate IS NOT NULL
 AND EXTRACT(YEAR_MONTH FROM CreatedDate) >= EXTRACT(YEAR_MONTH FROM CURDATE())-100
 GROUP BY DATE_FORMAT(CreatedDate, '%M')
 ORDER BY CreatedYearMonth";

//storing the result of the executed query
$result = $conn->query($estimates_query);

//initialize the array to store the processed data
$estimatesJsonArray = array();

//check if there is any data returned by the sql query
if ($result->num_rows > 0) {
//converting the results into an associative array
while ($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['date'] = $row['CreatedMonth'];
$jsonArrayItem['clientCostsTotal'] = $row['ClientCostsTotal'];
//append the above created object into the main array
array_push($estimatesJsonArray, $jsonArrayItem);
}
}

//close the connection to the database
$conn->close();

//set the response content type as json
header('Content-type: application/json');
//output the return value of json encode using the echo function
echo json_encode($estimatesJsonArray, JSON_PRETTY_PRINT);

这是JSON:

[
{
    "date": "February 2016",
    "clientCostsTotal": "21211.25"
},
{
    "date": "March 2016",
    "clientCostsTotal": "206996.25"
},
{
    "date": "April 2016",
    "clientCostsTotal": "74667.50"
},
{
    "date": "May 2016",
    "clientCostsTotal": "61128.75"
},
{
    "date": "June 2016",
    "clientCostsTotal": "267740.50"
},
{
    "date": "July 2016",
    "clientCostsTotal": "200946.75"
},
{
    "date": "August 2016",
    "clientCostsTotal": "0.00"
}
]

MySQL数据库中有另一列StatusVARCHAR类型)。它由以下值组成:新估计,已批准,已开票,等待开票,已取消,有客户,已提交成本。

我需要编写一个MySQL查询,它为我提供了构成SUM(ClientCostToDate) AS ClientCostsTotal的行的所有状态。然后,我需要计算每个类型的状态(新估计,已批准,已开票,等待结算,已取消,有客户,已提交成本)的数量。实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合将每个值放在单独的列中:

SELECT DATE_FORMAT(CreatedDate, '%M %Y') AS CreatedMonth,
       SUM(ClientCostToDate) AS ClientCostsTotal,
       SUM(status = 'New Estimate') as num_NewEstimate, 
       SUM(status = 'Approved') as num_Approved, 
       . . .
FROM Estimates
WHERE CreatedDate IS NOT NULL AND
      EXTRACT(YEAR_MONTH FROM CreatedDate) >= EXTRACT(YEAR_MONTH FROM CURDATE())-100
GROUP BY DATE_FORMAT(CreatedDate, '%M %Y')
ORDER BY CreatedYearMonth;