如何在PHP
或MySQL
中创建一个结果,以{2005}为例,并将所有结果相加
示例输入
-------------------------
Date \ Quantiti
-------------------------
12-05-2005 \ 5
-------------------------
23-08-2005 \ 8
-------------------------
11-02-2006 \ 4
-------------------------
26-09-2006 \ 2
-------------------------
示例输出
---------------------------
year \ Total
---------------------------
2005 \ 13
---------------------------
2006 \ 6
---------------------------
<?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 {
}
?>
答案 0 :(得分:1)
通过使用SUM()
对年份进行分组,您可以GROUP BY YEAR(date)
具有相同年份的所有量化。像这样的简单查询应该完成工作
SELECT SUM(Quantiti) as `total`,
YEAR(date) as `year`
FROM mytable
GROUP BY YEAR(date)
请注意,根据您的示例输出,返回的结果名为total
和year
。
答案 1 :(得分:0)
您可以使用SUM汇总数量,使用GROUP BY按年份对结果进行分组。
根据您的需求进行SQL查询:
SELECT YEAR(Date), SUM(Quantiti)
FROM mytaple
GROUP BY YEAR(Date)
所以你的代码是:
<?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 {
}
?>
答案 2 :(得分:-1)
分组依据年份和月份将实现此目标
GROUP BY YEAR(日期),MONTH(日期)