我有一个php函数来获取morris饼图的日期,它运行正常。
但现在我有更多数据(去年和今年前3个月的日期)。它现在显示重复的月份。在这种情况下,去年2月和今年的数据现在显示在同一个饼图上。
我想在php中编写一些mysql代码,只显示过去12个月。我有以下代码:
function writesql($rec) {
$year = date('Y') -1;
$month = date('m');
$lastyear = $year - $month; // I know this is a problem.It's subtracting the two variables
$sql = "";
$sql = $sql . " SELECT";
$sql = $sql . " YEAR(`value`)as 'Year',";
$sql = $sql . " MONTH(`value`)as 'Month',";
$sql = $sql . " `value` , ";
$sql = $sql . " COUNT(`value`) as 'Calls' ,";
$sql = $sql . " ROUND(SUM( `value` ),2) as 'Value'";
$sql = $sql . " FROM `table`";
$sql = $sql . " GROUP BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)" ;
$sql = $sql . " ORDER BY";
$sql = $sql . " YEAR(`value`),";
$sql = $sql . " MONTH(`value`)";
$sql = $sql." WHERE (`value`)='".$lastyear."'";// I also know this is wrong too but im lost as to how to fix it.
return $sql;
}
然后其余部分如下,我只想获取过去12个月的数据,我应该如何执行此操作。
答案 0 :(得分:3)
你可以WHERE value >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR);
这将显示截至当前日期的12个月。
答案 1 :(得分:0)
你很亲密。进行这些更改
$year = date('Y') -1; // This will give last year
$sql." WHERE YEAR(`value`)='".$year."'"
更新了查询
$sql = "
SELECT YEAR(`value`) as 'Year', MONTH(`value`) as 'Month', `value`,
COUNT(`value`) as 'Calls', ROUND(SUM( `value` ),2) as 'Value'
FROM `table`
WHERE YEAR(`value`) = '$year'
GROUP BY YEAR(`value`), MONTH(`value`)
ORDER BY YEAR(`value`), MONTH(`value`)";
答案 2 :(得分:0)
首先,我发现这更容易阅读:
$sql = "
SELECT YEAR(value) Year
, MONTH(value) Month
, value
, COUNT(value) Calls
, ROUND(SUM(value),2) Value
FROM `table`
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value)
WHERE (value) = '".$lastyear."'
";
但是这个查询在语法上是不正确的。所以这是一个语法正确的版本:
$sql = "
SELECT YEAR(`value`) Year
, MONTH(`value`) Month
, COUNT(value) Calls
, ROUND(SUM(value),2) Total_Value
FROM `table`
WHERE value = '".$lastyear."'
GROUP
BY YEAR(value)
, MONTH(value)
ORDER
BY YEAR(value)
, MONTH(value);
";
现在查看准备和绑定查询