2016-09-15 32 views
1

我有一个MySQL查询,按月将我的数据库中的所有ClientCostToDate行(类型为DECIMAL)相加,然后将数据作为JSON返回。在MySQL数据库的列中计数值的查询

我的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的行的所有状态。然后,我需要计算每种状态的数量(新估计,已批准,已开票,等待结算,已取消,有客户,已提交成本)。什么是完成这个最好的方法?

回答

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; 
+0

谢谢。这完全符合我喜欢的方式。为了获得所有'Status'值的总数,你会运行一个SUM(num_NewEstimate,num_Approved,...)吗?这是完成这一难题的最佳方式吗? – Liz

+1

@LizBanach:MySQL不允许你在同一个查询的SELECT列表中引用列别名。您可以使此查询成为内联视图(具有必需的性能损失),并在外部查询中引用列名称。或者,1)重复相同的表达式(即得到单独的计数),但将它们与加法运算符(+)组合,而不是使用逗号分隔符。或2)做另一个表达式,测试所有值SUM(状态IN('新估计','批准',...))AS num_in_status_list'。 – spencer7593

+0

谢谢你的指导@ spencer7593 – Liz