For each new year from date straing PHP MySQL
本问题已经有最佳答案,请猛点这里访问。
我如何在
XYK样本输入
1 2 3 4 5 6 7 8 9 10 11 | ------------------------- Date \ Quantiti ------------------------- 12-05-2005 \ 5 ------------------------- 23-08-2005 \ 8 ------------------------- 11-02-2006 \ 4 ------------------------- 26-09-2006 \ 2 ------------------------- |
XYK样本输出
1 2 3 4 5 6 7 | --------------------------- year \ Total --------------------------- 2005 \ 13 --------------------------- 2006 \ 6 --------------------------- |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $sql ="SELECT * FROM mytable ORDER BY date DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $date = $row["date"]; $quantiti = $row["quantiti"]; // here i need code for each new year } } else { } ?> |
您可以使用
请注意,根据示例输出,返回的结果命名为
您可以使用Sum来汇总数量,并使用Group By来按年份对结果进行分组。
您需要的SQL查询将是:
所以你的代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php $sql ="SELECT YEAR(Date) as y, SUM(Quantiti) as q FROM mytaple GROUP BY YEAR(Date)"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $date[] = $row["y"]; $quantiti[] = $row["q"]; } for($i<0; $i<count($date);$i++) { echo $date[$i]."/".$quantiti[$i]; } } else { } ?> |
按年和月分组将实现此目标
GROUP BY YEAR(Date), MONTH(Date)