2016-09-15 34 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