PHP MySQL从日期字符串的每年For each

For each new year from date straing PHP MySQL

本问题已经有最佳答案,请猛点这里访问。

我如何在PHPMySQL中创建一个结果,以显示2005年为例,并汇总所有结果

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 {


    }
?>


您可以使用GROUP BY YEAR(date)对年份进行分组,从而使同一年份的所有数量都为SUM()。像这样的简单查询应该可以完成这项工作

1
2
3
4
SELECT SUM(Quantiti) as `total`,
       YEAR(date) as `year`
FROM mytable
GROUP BY YEAR(date)

请注意,根据示例输出,返回的结果命名为totalyear


您可以使用Sum来汇总数量,并使用Group By来按年份对结果进行分组。

您需要的SQL查询将是:

1
2
3
SELECT YEAR(Date), SUM(Quantiti)
FROM mytaple
GROUP BY YEAR(Date)

所以你的代码是:

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)