0

我正在尝试在当前月份的可视折线图中显示三个广告系列的总和。目前,JSON 结果每天显示每个活动的正确结果,但每天显示三个。我无法在原始 SQL 语句中添加 SUM,因为我需要当月每日结果的总和,而不是整个月的总和。

如果我错了,请纠正我,但我相信这需要在while循环中完成。我还在学习 PHP,想不出解决方案。我尝试if, else if在循环中添加一些条件以while查找单个广告系列并将结果设置为一个变量,然后将其相加并用于替换该$monthlySEMClicksJSON变量,但无济于事。

我怎样才能做到这一点?

    // Current Month JSON
$monthQueryResultJSON = "SELECT * FROM AdWords_Reporting WHERE CampaignID IN('CAMP008', 'CAMP011', 'CAMP044') AND AveragePosition != '0' AND YEAR(date) = YEAR(NOW()) AND MONTH(date) = MONTH(NOW()) ORDER BY Date ASC";
$monthlyResultJSON = mysql_query($monthQueryResultJSON) or die(mysql_error());

$monthlySEMClicksJSON = '';
$monthlySEMImpressionsJSON = '';
$monthlySEMDateJSON = '';
$printClicksMonthlySEM = '';
$printToolTipMonthlySEM = '';
$printImpressionsMonthlySEM = '';
while($singleRowMonth = mysql_fetch_array($monthlyResultJSON)){
    $monthlySEMClicksJSON = $singleRowMonth['TotalClicks'];
    $monthlySEMImpressionsJSON = $singleRowMonth['TotalImpressions'];
    $monthlySEMDateJSON = $singleRowMonth['Date'];
    $printClicksMonthlySEM .= json_encode($monthlySEMClicksJSON).",";
    $printImpressionsMonthlySEM .= json_encode($monthlySEMImpressionsJSON).",";
    $printToolTipMonthlySEM .= json_encode("<b>Date:</b> " .$monthlySEMDateJSON . "<br /><b>Total Impressions:</b> " . $monthlySEMImpressionsJSON . "<br /><b>Total Clicks:</b> " .$monthlySEMClicksJSON).",";      
}
4

1 回答 1

2

将 SQL 中的日期格式化为月份,即'Ym'对此进行聚合。

SELECT 
sum(field1) as sfield1, sum(field2) as sfield2, date_format(date, '%Y%m') as dateaggregate 
FROM AdWords_Reporting WHERE CampaignID IN('CAMP008', 'CAMP011', 'CAMP044') 
AND AveragePosition != '0' AND YEAR(date) = YEAR(NOW()) AND MONTH(date) = MONTH(NOW()) 
Group by dateaggregate 
ORDER BY Date ASC"

(这不是经过测试的 SQL,只是一个提示!)

结果:每月的汇总值。这可以很容易地更改为任何时间范围,例如年、月、周、季度等。

此外:“日期”是 SQL 中的保留字,这样命名列不是一个好主意。

于 2013-05-28T16:24:08.980 回答